While looking at your code, why would one want to read class specific properties in a generic method?
The only solutions i see is to use Reflection, or create an abstract base class with a before save method and call that method in de Save() method. Add a generic type constraint to the DBObject class defining that T is of the basetype. This way you can add class specific functionality to a generic method. Something like this:
public abstract class Base
{
public virtual void BeforeSave()
{
}
}
public class User : Base
{
public string Name { get; set; }
public int Age { get; set; }
public override void BeforeSave()
{
// You can access your properties here
if (this.Name.Trim() == "")
throw new Exception("Name is mandatory!")
}
}
public class DBObject<T>
where T: Base
{
public void Save()
{
T.BeforeSave();
}
}
7
solved How to capture value OOPS & Generic [closed]