C#Unity中的克隆类,这两个代码片段是否有捷径?

问题描述

因此,我正在一个设备系统上工作,该设备系统上有一些Item模板类,而不是每次为此实例化一个新项目时都想克隆:

public Item(Item clone)
{
    this.name = clone.name;
    this.description = clone.description;
    this.icon = clone.icon;
    this.mesh = clone.mesh;
    this.weight = clone.weight;
    this.price = clone.price;
}

这部分可以用一行格式写得更聪明吗,我不必在每次添加新参数时都进行更新?

接下来,我从Item继承了一堆子类,并克隆这些子类,我制作了一个静态类:

public static dynamic EquipmentClone(dynamic toClone)
{
    switch (toClone)
    {
        case Item_Armor item: return new Item_Armor(toClone);
        case Item_Weapon item: return new Item_Weapon(toClone);
        case Item_Equipment item: return new Item_Equipment(toClone);
        case Item item: return new Item(toClone);
        default: return null;
    }

}

这样,我可以将一个项目传递给该方法,它将实例化并输出相应类型的克隆。可以将这部分制成一个衬板吗?也许使用泛型?

解决方法

尝试一下:

    private object DeepCopy(object obj) {
            if (obj == null)
                return null;
            Type type = obj.GetType();

            if (type.IsValueType || type == typeof(string)) {
                return obj;
            }
            else if (type.IsArray) {
                Type elementType = Type.GetType(
                     type.FullName.Replace("[]",string.Empty));
                var array = obj as Array;
                Array copied = Array.CreateInstance(elementType,array.Length);
                for (int i = 0; i < array.Length; i++) {
                    copied.SetValue(DeepCopy(array.GetValue(i)),i);
                }
                return Convert.ChangeType(copied,obj.GetType());
            }
            else if (type.IsClass) {

                object toret = Activator.CreateInstance(obj.GetType());
                FieldInfo[] fields = type.GetFields(BindingFlags.Public |
                            BindingFlags.NonPublic | BindingFlags.Instance);
                foreach (FieldInfo field in fields) {
                    object fieldValue = field.GetValue(obj);
                    if (fieldValue == null)
                        continue;
                    field.SetValue(toret,DeepCopy(fieldValue));
                }
                return toret;
            }
            else
                throw new ArgumentException("Unknown type");
        }

在顶部添加:

using System.Reflection;

例如,将返回的对象强制转换为新类型,例如:

Item_Armor clonedVarName = (Item_Armor)DeepCopy(cloneSourceVarName);

您不必逐个字段复制类元素,这是上述方法处理的。 如果这不起作用,here有一些想法。我从那里得到了发布的示例,并直接为我工作。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...