【发布时间】:2012-12-09 18:46:02
【问题描述】:
我正在尝试使用反射设置一个数组字段,如下所示:
FieldInfo field = ...
A[] someArray = GetElementsInSomeWay();
field.SetValue(this, someArray);
该字段的类型为B[]。 B 继承自 A 并且 B 的确切类型在编译时是未知的。
GetElementsInSomeWay() 返回 A[] 但里面的真正元素都是 B 的。 GetElementsInSomeWay() 是库方法,不能更改。
我最多能做的就是得到B和System.Type type = field.FieldType.GetElementType()。
但是我不能将数组转换为所需的类型,例如
someArray as type[] 因为[] 在声明数组类型之前需要一个确切的类型。或者我在这里错过了什么?如果使用System.Type 变量在运行时已知类型,我可以声明某种类型的数组吗?
直接执行会产生以下错误(这里 A 是 UnityEngine.Component 和 B 是 AbilityResult 也可以是其他几十个类之一,全部继承(可能通过长继承链) 来自UnityEngine.Component):
ArgumentException: Object type UnityEngine.Component[] cannot be converted to target type: AbilityResult[]
Parameter name: val
System.Reflection.MonoField.SetValue (System.Object obj, System.Object val, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Globalization.CultureInfo culture) (at /Applications/buildAgent/work/3df08680c6f85295/mcs/class/corlib/System.Reflection/MonoField.cs:133)
System.Reflection.FieldInfo.SetValue (System.Object obj, System.Object value) (at /Applications/buildAgent/work/3df08680c6f85295/mcs/class/corlib/System.Reflection/FieldInfo.cs:150)
【问题讨论】:
-
要么我不明白,要么这是不可能的。该字段不能是
B[]类型,其中B在编译时未知。
标签: c# arrays reflection system.type fieldinfo