Copy properties between objects using reflection a

2019-07-23 03:30发布

This is my code where I create a "copy" of one object (Entity) into a custom object.
It copies just properties with the same name in both source and target.

My problem is when an Entity has a navgiaton to another Entity, for this case I added a custom attribute that I add above the property in the custom class.

For example the custom class looks like:

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

 }

The problem is in targetProp.CopyPropertiesFrom(sourceProp); line, when I try to call extension method again (to copy the nested object) ,because the type is determined on run time, extension method couldn't resolved on compile time.

Maybe I am missing something...

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条回答
Lonely孤独者°
2楼-- · 2019-07-23 03:57

Either you need to cast targetProperty to BaseDataItemModel so you can call the extension method on it (edit: as in agent-j's answer), or otherwise you could just forget about that base class. Why does your reflection algorithm need it? It could work on any class, and is directed purely by the attributes on properties.

And if it works on any object, it shouldn't be an extension method.

查看更多
Emotional °昔
3楼-- · 2019-07-23 04:21

You'll have to cast first.

((BaseDataItemModel)targetProp).CopyPropertiesFrom(sourceProp); 
查看更多
登录 后发表回答