2017-05-25 69 views
0

我需要将一个对象的属性复制到另一个对象,两个对象可以是不同的类型,可以具有相同名称的属性。这些属性也可以是复杂的类型。复制选择属性到其他类型的对象

我是能够实现简单TYPE性质,我怎么过的,我无法实现这一复杂类型的复制功能..像见下面的示例代码段

[TestClass] 
public class PropAssignTest 
{ 
    [TestMethod] 
    public void Test() 
    { 
     Test1 t1 = new Test1() { Prop1 = "test", TestName = new Test3 { Name = "santosh" } } ; 
     Test2 t2 = new Test2(); 
     Assign<Test1, Test2>(t1, t2, e => e.Prop1); 
     Assign<Test1, Test2>(t1, t2, e => e.TestName.Name);//this doesnot work !! 
    } 

    private void Assign<T1,T2>(T1 T1Obj, T2 T2Obj, Expression<Func<T1, object>> memberLamda) 
    { 
     var memberSelectorExpression = memberLamda.Body as MemberExpression; 
     if (memberSelectorExpression != null) 
     { 
      var property = memberSelectorExpression.Member as PropertyInfo; 
      if (property != null) 
      { 
       T2Obj.GetType().GetProperty(property.Name).SetValue(T2Obj, property.GetValue(T1Obj)); 
      } 
     } 
    } 

在上面的代码中,我想复制e.TestName.Name ,其中TestName是一个复杂类型的对象,其中我只需要复制TestName,TestName的Name属性就可以定义许多属性。

任何建议...

感谢

+1

只需使用AutoMapper :) –

+0

不,我不能,我One.Because只想复制选定的属性,Automapper会尝试复制所有属性。 –

+1

@SantoshVaza你可以配置AutoMapper如何将T1映射到T2 –

回答

4

使用AutoMapper,而忽略你不希望映射的成员。

config.CreateMap<Person, Employee>() 
    .ForMember(d => d.Name, o => o.MapFrom(s => s.FullName)) 
    .ForMember(d => d.Age, o => o.Ignore()); 
+0

谢谢@Kevin,但是我不想使用automapper –

0

您可以尝试使用@Kevin提到的AutoMapper。如果你仍然需要一个自定义的方法,你可以试试这个。注意:它将值复制到目标对象本身的属性中,并且不像表达式树中那样查找属性。

private static void Assign<T1, T2>(T1 T1Obj, T2 T2Obj, Expression<Func<T1, object>> memberLamda) 
{ 
    var memberSelectorExpression = memberLamda.Body as MemberExpression; 

    if (memberSelectorExpression != null) 
    { 
     var sourceProperty = memberSelectorExpression.Member as PropertyInfo; 

     if (sourceProperty != null) 
     { 
      var targetProperty = T2Obj.GetType().GetProperty(sourceProperty.Name); 

      if (targetProperty != null) 
      { 
       targetProperty.SetValue(T2Obj, GetValue(T1Obj, memberSelectorExpression)); 
      } 
     } 
    } 
} 

public static object GetValue<T>(T source, MemberExpression expr) 
{ 
    var sourceProperty = expr.Member as PropertyInfo; 

    var nextExpression = expr.Expression as MemberExpression; 

    if (nextExpression == null) 
    { 
     return sourceProperty.GetValue(source); 
    } 

    var sourcePart = GetValue(source, nextExpression); 
    return sourceProperty.GetValue(sourcePart); 
} 
+0

感谢您的回答,请尝试。 targetProperty == null检查似乎是一个小故障,如果T2Obj已经有一个同名的属性 –