使用反射和扩展方法复制对象之间的属性

时间:2011-08-05 18:53:11

标签: c# reflection extension-methods

这是我的代码,我在其中创建一个对象(实体)的“副本”到自定义对象中 它只复制源和目标中具有相同名称的属性。

我的问题是当一个实体有一个navgiaton到另一个实体时,在这种情况下,我添加了一个自定义属性,我在自定义类的属性上面添加。

例如,自定义类看起来像:

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);行,当我尝试再次调用扩展方法(复制嵌套对象)时,因为类型是在运行时确定的,扩展方法无法在编译时解析。 / p>

也许我错过了什么......

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);
   }
}

2 个答案:

答案 0 :(得分:1)

你必须先施展。

((BaseDataItemModel)targetProp).CopyPropertiesFrom(sourceProp); 

答案 1 :(得分:0)

您需要将targetProperty投射到BaseDataItemModel,以便您可以在其上调用扩展方法(编辑:在代理-j的答案中),否则您可以忘记那个基类。为什么你的反射算法需要它?它可以在任何类上工作,并且完全由属性上的属性指导。

如果它适用于任何object,则它不应该是扩展方法。