merging two objects in C#

后端 未结 6 1894
無奈伤痛
無奈伤痛 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:37

    I've written my own class for this purpose: ObjectMerger.

    Basically it uses reflections (and may be slow because of that). It also contains more features e.g. parsing objects for cyclic references and merge them too. My ObjectMerger also contains mechanism to handle more complex classes like Delegate or MemberInfo. Those will be copied completely, other objects in the class are recursively merged.

    The Syntax is like:

    var initialInstance = new MyObjectBase(); // Initialize first object
    var properInstance = new MyObjectWithAlgorithms(); // Initialize second object
    var result = ObjectMerger.MergeObjects(properInstance, initialInstance); // Merge Objects into type of "properInstance"
    

    I'm sorry to say that it is NOT FOR USE AS IS, because some external libraries are missing in the repository at the moment due to limitations in my company, but they can easily be rewritten. I hope a can add them in future.

提交回复
热议问题