开发者

Copy properties between objects using reflection and extesnion method

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 = t开发者_开发知识库argetProperty.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);
   }
}


You'll have to cast first.

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜