Copy two identical object with different namespaces (recursive reflection)

后端 未结 7 1426
我寻月下人不归
我寻月下人不归 2021-01-06 19:22

I\'m working in c# with several workspaces that have one specific class which his always the same in each workspace. I would like to be able have a copy of this class to be

相关标签:
7条回答
  • 2021-01-06 20:24

    This problem can be elegantly solves using Protocol Buffers because Protocol Buffers do not hold any metadata about the type they serialize. Two classes with identical fields & properties serialize to the exact same bits.

    Here's a little function that will change from O the original type to C the copy type

    static public C DeepCopyChangingNamespace<O,C>(O original)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            Serializer.Serialize(ms, original);
            ms.Position = 0;
            C c = Serializer.Deserialize<C>(ms);
            return c;
        }
    }
    

    usage would be

    namespace1.class1 orig = new namespace1.class1();
    
    namespace2.class1 copy = 
        DeepCopyChangingNamespace<namespace1.class1, namespace2.class1>(orig);
    
    0 讨论(0)
提交回复
热议问题