【发布时间】:2019-10-20 17:59:08
【问题描述】:
我正在使用反射在运行时复制任何自定义类的对象。我正在使用FieldInfo 获取所有字段,然后根据它们的类型正确复制它们。
我可以在复制算法开始时使用的唯一类型是System.Object(又名object)。
我做了很多类型检查。所以当我的检查方法说这个特定的对象是一些简单的一维数组时,它是数组,毫无疑问。但是我只能在运行时访问该数组中的元素类型。
我确实像这样成功复制了List<type known at runtime>:
public object Get_ListCopy(object original)
{
Type elementType = original.GetType().GetGenericArguments()[0];
Type listType = typeof(List<>).MakeGenericType(elementType);
object copy = Activator.CreateInstance(listType);
var copyIList = copy as IList;
foreach (var item in original as IEnumerable)
copyIList.Add(item);
copy = copyIList;
return copy;
}
然后我尝试重写简单数组的方法:
public object Get_ArrayCopy(object original)
{
Type elementType = original.GetType().GetElementType(); // difference here
Type listType = typeof(List<>).MakeGenericType(elementType);
object copy = Activator.CreateInstance(listType);
var copyIList = copy as IList;
foreach (var item in original as IEnumerable)
copyIList.Add(item);
copy = Enumerable.Range(0, copyIList.Count).Select(i => copyIList[i]).ToArray(); // difference here
return copy;
}
但是当使用FieldInfo.SetValue(copyObject, convertedValue) // where convertedValue is object copy from the method above为字段赋值时会返回异常:
System.ArgumentException: 'Object of type 'System.Object[]' cannot be converted to type 'System.Int32[]'.'
对于该特定示例,数组如下所示:
public int[] Array = { 1, 2, 3 };
最后一件事:我知道如何使用泛型方法和 MethodInfo ...MakeGenericMethod(...).Invoke 来解决这个问题,我只是认为可以避免(也许我错了)。也不能使用序列化。
【问题讨论】:
-
为什么不直接打电话给
ToArraycopyList? -
@HimBromBeere IList 没有 ToArray 方法。
标签: c# reflection type-conversion