我有一个类,我正在尝试对其运行深层复制。此类的成员之一是“MeshContainers”,它是 MeshContainerCollection 的一个实例。
MeshContainerCollection<> 继承 self 的 SceneObjectCollection<> 类,该类继承自 List<>
我注意到源对象在 meshcontainercollection 中有 1 个项目,而克隆对象有 0 个项目。 在逐步执行 DeepCopy 过程时,我注意到当我尝试获取 MeshContainerCollection 的字段时,它找不到任何字段。 现在 MeshContainerCollection 没有任何直接字段(只有继承的字段)所以我认为这是问题所在。
但我使用:
FieldInfo[] fields = type.GetFields(BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance);
哪个(afaik)也应该返回私有(private)继承成员。 我查看了现有的 BindingFlags,但无法弄清楚是否应该使用另一个 BindingFlag 来获取继承的私有(private)字段。
谁能告诉我如何进行真正的深拷贝?
我正在使用的深度复制方法:
private static object Process(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(Process(array.GetValue(i)), i);
}
return Convert.ChangeType(copied, obj.GetType());
}
else if (type.IsClass)
{
object toret = FormatterServices.GetUninitializedObject(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, Process(fieldValue));
}
return toret;
}
else
throw new ArgumentException("Unknown type");
}
EDIT1:我不喜欢通过序列化而是通过反射来做到这一点。
最佳答案
如 GetFields documentation 中所述,
private fields on base classes are not returned.
试试这个方法:
public static IEnumerable<FieldInfo> GetAllFields(this Type type)
{
IEnumerable<FieldInfo> fields = type.GetFields(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (type.BaseType == null)
return fields;
else
return GetAllFields(baseType).Concat(fields);
}
(你可能想重写它以避免所有的枚举和连接,但你明白了)
关于c# - 我的深拷贝不是真正的深拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11100924/