1

I'm trying to clone instances of a derived class, but somehow it doesn't work well. The cloning method is:

public static T CloneFieldsAndProperties<T>(T input)
{
    T result = (T)Activator.CreateInstance(typeof(T));
    PropertyInfo[] listOfProps = typeof(T).GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.CreateInstance);
    FieldInfo[] listOfFields = typeof(T).GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.CreateInstance);
    foreach (PropertyInfo prop in listOfProps) prop.SetValue(result, prop.GetValue(input, null), null);
    foreach (FieldInfo field in listOfFields) field.SetValue(result, field.GetValue(input));
    return result;
}

As you can see, I added many BindingFlags because it wasn't working. But to no avail.

It does work in a simple case:

MyclassA1 a1 = new MyclassA1();
MyclassA a = CloneFieldsAndProperties(a1);
if (a is MyclassA1) Text = "Works";

Where:

class MyclassA
{
    public int i;
}

class MyclassA1 : MyclassA
{
    public int i1;
}

But in my real program it doesn't. The real program's classes' declarations are long so I'm not posting them here. What might be the problem?

4

3 回答 3

3

很久以前我有同样的问题。经过大量谷歌搜索后,对我来说唯一真正的解决方案是对其进行序列化和反序列化。这不是一个糟糕的解决方案,您只会损失一点性能,只需这样做:

将此标签添加到您的班级:

[Serializable()]
public class a
{

}

然后你可以创建一个这样的函数:

public object Clone()
{
    IO.MemoryStream mem = new IO.MemoryStream();
    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter form = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
    form.Serialize(mem, this);
    mem.Position = 0;
    return form.Deserialize(mem);
}
于 2012-04-22T14:36:02.097 回答
2

如果您需要浅克隆,只需使用Object.MemberwiseClone. 如果您需要深度克隆,请序列化然后反序列化您的对象(例如使用BinaryFormatteror DataContractSerializer)。这将解决诸如循环和交叉引用之类的问题。

于 2012-04-23T07:33:49.683 回答
0

这将起作用并且可能比序列化方法更快:

代码:

using System;

namespace Cloning
{
    class Program
    {
        static void Main(string[] args)
        {
            Derived d = new Derived() { property = 1, field = 2, derivedProperty = 3, derivedField = 4 };
            Base b = new Derived(d);

            // Change things in the derived class.
            d.property = 5;
            d.field = 6;
            d.derivedProperty = 7;
            d.derivedField = 8;

            // Output the copy so you know it's not shallow.
            Console.WriteLine((b as Derived).property);
            Console.WriteLine((b as Derived).field);
            Console.WriteLine((b as Derived).derivedProperty);
            Console.WriteLine((b as Derived).derivedField);

            Console.ReadLine();
        }

        class Base
        {
            public int property { get; set; }
            public int field;
        }

        class Derived : Base
        {
            public Derived() { }

            public Derived(Derived d)
            {
                // Perform the deep copy here.
                // Using reflection should work, but explicitly stating them definitely
                // will, and it's not like it's not all known until runtime.
                this.property = d.property;
                this.field = d.field;
                this.derivedProperty = d.derivedProperty;
                this.derivedField = d.derivedField;
            }

            public int derivedProperty { get; set; }
            public int derivedField;
        }

    }
}

测试:

http://goo.gl/pQnAL

输出:

1
2
3
4

注释:

我真的会想象这不仅适用于微不足道的情况,但可能不会:

public static T CloneFieldsAndProperties<T>(T input)
{
    T result = (T)Activator.CreateInstance(input.GetType());

    PropertyInfo[] properties = input.GetType().GetProperties();
    FieldInfo[] fields = input.GetType().GetFields();

    foreach (PropertyInfo property in properties)
        property.SetValue(result, property.GetValue(input, null), null);
    foreach (FieldInfo field in fields)
        field.SetValue(result, field.GetValue(input));

    return result;
}
于 2012-04-22T15:19:36.060 回答