合并在C#中的两个对象 [英] merging two objects in C#

查看:849
本文介绍了合并在C#中的两个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象模型MyObject的各种属性。在一个点上,我有这MyObject来的两个实例:实例A和实例B,我想复制和取代的实例上的属性与实例b,如果实例B具有非空值

I have an object model MyObject with various properties. At one point, I have two instances of these MyObject: instance A and instance B. I'd like to copy and replace the properties in instance A with those of instance B if instance B has non-null values.

如果我只用了1级的有3个属性,没问题,我可以很容易硬code它(这是我开始做)。但事实上,我有12个不同的对象模型有大约10属性每个。

If I only had 1 class with 3 properties, no problem, I could easily hard code it (which is what I started doing). But I actually have 12 different object models with about 10 properties each.

有什么好办法做到这一点?

What's good way to do this?

推荐答案

更新 使用 AutoMapper ,而是如果你需要调用此方法很多。 Automapper建立动态方法使用 Reflection.Emit的键,会比思考快多了。

Update Use AutoMapper instead if you need to invoke this method a lot. Automapper builds dynamic methods using Reflection.Emit and will be much faster than reflection.'

您可以使用反射复制的属性值:

You could copy the values of the properties using reflection:

    public void CopyValues<T>(T target, T source)
    {
        Type t = typeof(T);

        var properties = t.GetProperties().Where(prop => prop.CanRead && prop.CanWrite);

        foreach (var prop in properties)
        {
            var value = prop.GetValue(source, null);
            if (value != null)
                 prop.SetValue(target, value, null);
        }
    }

我做了它的通用,以确保类型安全。如果你想包括私人属性,你应该使用的重写<一href="http://msdn.microsoft.com/en-us/library/system.type.getproperties.aspx">Type.GetProperties(),指定绑定标志。

这篇关于合并在C#中的两个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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