【问题标题】:Copy properties between objects using reflection and extesnion method使用反射和扩展方法在对象之间复制属性
【发布时间】: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);
   }
}

【问题讨论】:

标签: c# reflection extension-methods


【解决方案1】:

你必须先投射。

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

【讨论】:

  • 哈哈,难以置信,我之前试过,但没有用,所以我又试了一次,我发现了什么? Lecturer 没有从 BaseDataItemModel 继承... P.s (BaseDataItemModel)sourceProp 是错误的,因为 sourceProp 是一个 EF 实体(不从 BaseDataItemModel 继承)
【解决方案2】:

您需要将targetProperty 转换为BaseDataItemModel 以便您可以在其上调用扩展方法(edit:如 agent-j 的回答),否则您可能会忘记这一点基类。为什么你的反射算法需要它?它可以在任何类上工作,并且完全由属性上的属性来指导。

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

【讨论】:

  • 或者至少将它隔离在一个特定的命名空间中,这样你就可以在特定的受限区域中污染object
  • 我只想限制从 BaseDataItemModel 继承的对象的扩展
猜你喜欢
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 2017-01-17
  • 1970-01-01
  • 1970-01-01
  • 2020-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多