簡體   English   中英

使用反射和拉伸方法在對象之間復制屬性

[英]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); 

您需要將targetPropertyBaseDataItemModel以便可以在其上調用擴展方法( edit :如agent-j的回答所示),否則您可能會忘記該基類。 為什么您的反射算法需要它? 它可以在任何類上工作,並且僅由屬性上的屬性指導。

而且,如果它適用於任何object ,則不應將其作為擴展方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM