Now, I am working on ASP.NET MVC 2. I just found some serious problem about View Model class that derives from base class in Model project. Every time when I fetch data from database, I have to cast it to View Model instance that is not possible in most OOP language.
Base class
public class MyBaseClass
{
public string ID { get;set; }
public string Value { get;set; }
}
Derived class
public class MyDerivedClass : MyBaseClass, ISomeInterface
{
// logic for My Derived Class
}
However, I try to create some method that copy all readable property from instance of base class to instance of derived class like the following code.
public static TDerived CastObject<TBase, TDerived>(TBase baseObj)
{
Type baseType = typeof(TBase);
Type derivedType = typeof(TDerived);
if (!baseType.IsAssignableFrom(derivedType))
{
throw new Exception("TBase must be a parent of TDerived.");
}
TDerived derivedObj = Activator.CreateInstance<TDerived>();
foreach (PropertyInfo pi in baseType.GetProperties())
{
if (pi.CanRead)
{
PropertyInfo derivedProperty = derivedType.GetProperty(pi.Name);
if (derivedProperty.CanWrite)
{
derivedProperty.SetValue(derivedObj, pi.GetValue(baseObj, null), null);
}
}
}
return derivedObj;
}
But I do not sure about the above code that will work great on large-scale website and there are a lot of feature in DLR of C# 4.0 that I do not know.
Do you have any idea for converting item by using C# 4.0?
Thanks,