.net 为什么这种克隆不起作用?

mftmpeh8  于 2023-08-08  发布在  .NET
关注(0)|答案(3)|浏览(108)

我试图克隆一个派生类的示例,但不知何故,它工作得不好。克隆的方法是:

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;
}

字符串
正如您所看到的,我添加了许多BindingFlags,因为它不工作。但无济于事。
它在一个简单的情况下 * 确实 * 起作用:

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


其中:

class MyclassA
{
    public int i;
}

class MyclassA1 : MyclassA
{
    public int i1;
}


但在我的真实的程序中却不是。真实的的程序的类的声明很长,所以我不把它们放在这里。有什么问题吗?

ecbunoof

ecbunoof1#

很久以前我也有同样的问题。对我来说,在大量的谷歌搜索之后,唯一真实的的解决方案是序列化和反序列化它。这不是一个糟糕的解决方案,你只会损失一点点性能,就像这样做:
将此标记添加到您的类:

[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);
}

ycggw6v2

ycggw6v22#

如果您需要一个浅克隆,只需使用Object.MemberwiseClone。如果你需要一个深度克隆,序列化然后反序列化你的对象(例如使用JsonSerializer)。

1hdlvixo

1hdlvixo3#

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

验证码:

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;
}

相关问题