现在,我正在努力ASP.NETMVC 2。我刚在模型项目中发现了一些关于从基类派生的视图模型类的严重问题。每次从数据库中获取数据时,我都必须将其转换为视图模型实例,这在大多数OOP语言中是不可能的。
基类
public class MyBaseClass
{
public string ID { get;set; }
public string Value { get;set; }
}
派生类
public class MyDerivedClass : MyBaseClass, ISomeInterface
{
// logic for My Derived Class
}
但是,我尝试创建一些方法,将所有可读属性从基类的实例复制到派生类的实例,如下面的代码所示。
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;
}
但是我不确定上面的代码是否能在大型网站上很好地工作,而且在C#4.0的DLR中有很多我不知道的特性。
谢谢,