Copy two identical object with different namespace

2020-03-05 03:34发布

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 able to work with it without dealing with namespaces differences. example :

namespace1 {
    class class1{
        public class2;
    }

    class class2{
        public string;
    }

}

namespace2 {
    class class1{
        public class2;
    }

    class class2{
        public string;
    }
}

In my copied Class I've got a function to copy all data's to one of the namespace's class. It's working if i only have c# standard types. I got exeption ( "Object does not match target type." ) as soon as I'm dealing with class2 object (which is also from different namespaces)

public Object toNamespaceClass(Object namespaceClass)
{
    try
    {
        Type fromType = this.GetType();
        Type toType = namespaceClass.GetType();

        PropertyInfo[] fromProps = fromType.GetProperties();
        PropertyInfo[] toProps = toType.GetProperties();

        for (int i = 0; i < fromProps.Length; i++)
        {
            PropertyInfo fromProp = fromProps[i];
            PropertyInfo toProp = toType.GetProperty(fromProp.Name);
            if (toProp != null)
            {
                toProp.SetValue(this, fromProp.GetValue(namespaceClass, null), null);
            }
        }

    }
    catch (Exception ex)
    {
    }
    return namespaceClass;
}

Anyone do have any idea of how to deal with this kind of "recursivity reflection".

I hope eveything is understandable.

Thanks, Bye!

Edit : I think i got it solved (at least in my mind), I'll try the solution back at work tomorrow. Taking my function out of my class and using it recursively if a property is not a standard type is maybe the solution.

标签: c# reflection
7条回答
不美不萌又怎样
2楼-- · 2020-03-05 04:08

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);
查看更多
登录 后发表回答