将选择的属性复制到其他类型的对象 [英] copy chosen properties to object of other type

查看:62
本文介绍了将选择的属性复制到其他类型的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to copy properties of one object to another, both objects can be of different type, can have properties of same name. These property can also be of complex type.

我能够实现简单的TYPE属性的复制功能,但是我却无法实现复杂类型的复制功能.就像下面的示例代码片段

I was able to achieve the copy feature for simple TYPE properties, how ever i am unable to achieve this for complex types.. like see below sample snippet

[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的Name属性,但是TestName可以定义许多属性.

In above code i want to copy e.TestName.Name, where TestName is a complex type object, wherein i only need to copy Name property of TestName, TestName can however define many properties.

任何建议...

谢谢

推荐答案

使用 AutoMapper 并忽略您不使用的成员不想地图.

Use AutoMapper and ignore the members you don't want to map.

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

这篇关于将选择的属性复制到其他类型的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆