merging two objects in C#

后端 未结 6 1893
無奈伤痛
無奈伤痛 2020-11-29 07:06

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 p

6条回答
  •  日久生厌
    2020-11-29 07:32

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

    I've made it generic to ensure type safety. If you want to include private properties you should use an override of Type.GetProperties(), specifying binding flags.

提交回复
热议问题