使用不同的命名空间复制两个相同的对象(递归反射)

Ale*_*xis 3 c# reflection

我在c#中工作,有几个工作区有一个特定的类,在每个工作区中它总是相同的.我希望能够拥有此类的副本,以便能够使用它而无需处理命名空间差异.例如:

namespace1 {
    class class1{
        public class2;
    }

    class class2{
        public string;
    }

}

namespace2 {
    class class1{
        public class2;
    }

    class class2{
        public string;
    }
}
Run Code Online (Sandbox Code Playgroud)

在我复制的类中,我有一个函数将所有数据复制到命名空间的类之一.如果我只有c#标准类型,它会工作.一旦我处理class2对象(也来自不同的命名空间),我得到了exeption("对象与目标类型不匹配.")

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;
}
Run Code Online (Sandbox Code Playgroud)

任何人都知道如何处理这种"递归反射".

我希望eveything是可以理解的.

谢谢再见!

编辑:我想我已经解决了(至少在我的脑海里),我明天会在工作中尝试解决方案.如果属性不是标准类型,可以将我的函数从我的类中取出并递归使用它可能是解决方案.

Pet*_*err 6

BinaryFormatter在.Net 4.5中不起作用,因为它记住了实例创建的类的类型.但是对于JSON格式,它没有.JSON序列化程序由Microsoft在DataContractJosnSerializer中实现.

这有效:

    public static T2 DeepClone<T1, T2>(T1 obj)
    {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T1));
        DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(T2));

        using (var ms = new MemoryStream())
        {
            serializer.WriteObject(ms, obj);
            ms.Position = 0;

            return (T2)deserializer.ReadObject(ms);
        }
    }
Run Code Online (Sandbox Code Playgroud)

用法如下:

   var b = DeepClone<A, B>(a);
Run Code Online (Sandbox Code Playgroud)


小智 5

我有类似的问题.我必须使用类似的类,但仅在命名空间方面有所不同.作为一个快速的解决方案,我在下面的步骤中执

  1. 将源类序列化为XML.
  2. 在SerializedXML中,将源命名空间替换为目标命名空间.
  3. 使用目标类型进行DeSerialize.

我知道上面的方式有性能开销,但它实现快速且无错误.