C#FieldInfo.SetValue我试图使用反射像这样设置的阵列字段:与阵列参数和任意元素类型
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'在编译时不知道。 –