[英]Copy properties between objects using reflection and extesnion method
这是我的代码,在其中将一个对象(实体)“复制”到自定义对象中。
它仅复制源和目标中具有相同名称的属性。
我的问题是,当一个实体与另一个实体有导航关系时,在这种情况下,我添加了一个自定义属性,该属性添加到自定义类中的属性上方。
例如,自定义类如下所示:
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);
}
}
您必须先进行投射。
((BaseDataItemModel)targetProp).CopyPropertiesFrom(sourceProp);
您需要将targetProperty
为BaseDataItemModel
以便可以在其上调用扩展方法( edit :如agent-j的回答所示),否则您可能会忘记该基类。 为什么您的反射算法需要它? 它可以在任何类上工作,并且仅由属性上的属性指导。
而且,如果它适用于任何object
,则不应将其作为扩展方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.