【发布时间】:2011-08-06 03:05:39
【问题描述】:
这是我的代码,我将一个对象(实体)的“副本”创建到自定义对象中。
它只复制源和目标中具有相同名称的属性。
我的问题是当一个实体有一个到另一个实体的导航时,对于这种情况,我添加了一个自定义属性,我在自定义类的属性上方添加了该属性。
例如自定义类如下所示:
public class CourseModel:BaseDataItemModel
{
public int CourseNumber { get; set; }
public string Name { get; set; }
LecturerModel lecturer;
[PropertySubEntity]
public LecturerModel Lecturer
{
get { return lecturer; }
set { lecturer = value; }
}
public CourseModel()
{
lecturer = new LecturerModel();
}
}
问题出在targetProp.CopyPropertiesFrom(sourceProp); 行,当我尝试再次调用扩展方法(复制嵌套对象)时,由于类型是在运行时确定的,扩展方法无法在编译时解决。
也许我错过了什么......
public static void CopyPropertiesFrom(this BaseDataItemModel targetObject, object source)
{
PropertyInfo[] allProporties = source.GetType().GetProperties();
PropertyInfo targetProperty;
foreach (PropertyInfo fromProp in allProporties)
{
targetProperty = targetObject.GetType().GetProperty(fromProp.Name);
if (targetProperty == null) continue;
if (!targetProperty.CanWrite) continue;
//check if property in target class marked with SkipProperty Attribute
if (targetProperty.GetCustomAttributes(typeof(SkipPropertyAttribute), true).Length != 0) continue;
if (targetProperty.GetCustomAttributes(typeof(PropertySubEntity), true).Length != 0)
{
//Type pType = targetProperty.PropertyType;
var targetProp = targetProperty.GetValue(targetObject, null);
var sourceProp = fromProp.GetValue(source, null);
targetProp.CopyPropertiesFrom(sourceProp); // <== PROBLEM HERE
//targetProperty.SetValue(targetObject, sourceEntity, null);
}
else
targetProperty.SetValue(targetObject, fromProp.GetValue(source, null), null);
}
}
【问题讨论】:
-
ValueInjector 可能会为您节省一些时间valueinjecter.codeplex.com
标签: c# reflection extension-methods