이제 ASP.NET MVC 2에서 작업하고 있습니다. Model 프로젝트의 기본 클래스에서 파생 된 View Model 클래스에 대해 심각한 문제가 발견되었습니다. 데이터베이스에서 데이터를 가져올 때마다 대부분의 OOP 언어에서 불가능한 View Model 인스턴스로 캐스팅해야합니다.C# 4.0에서 기본 클래스 인스턴스와 파생 클래스 인스턴스의 가장 좋은 방법은 무엇입니까?
기본 클래스
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의 기능이 많이가있는 것입니다 위의 코드에 대해 확실하지 않습니다.
C# 4.0을 사용하여 항목을 변환 할 생각이 있습니까?
감사합니다,
모든 값을 파생 클래스에 복사하려는 이유를 설명 할 수 있습니다. – Bobby
체크 인스턴스 유형에 인터페이스가 있거나 없는지 다른 코드가 있기 때문에 생성 된 코드의 일부이기 때문에 기본 클래스를 수정할 수 없습니다. –