目标
我有一个 object[]Source、object Target 和 FieldInfo Var(Var.FieldType.IsArray 为真)。我想运行 Var.SetValue(Target,Source)。但是,我无法转换“object[]”->“anotherType[]”
样品运行
object[]Source=new object[2]{"Hello","World"};
Var.SetValue(Target,Source); //Cannot Convert "object[]"->"string[]"
[注意:我希望能够使用 int、double、float 等。否则,这个问题将非常简单]
研究
使用 Var: 无法使用,因为无法创建 var 数组
使用泛型:
这适用于
myField.SetValue(target,GenericCastArray<string>(source));
但是,它不适用于
Type someType=typeof(string); //or int, or float
(myfield.SetValue(target,GenericCastArray< someType > (source))
* http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/fe14d396-bc35-4f98-851d-ce3c8663cd79/ * 返回空引用异常,我认为在 this.GetType()
编辑:Meh 解决方案 根据评论,不可能从 object[] 转换为 string[]。但是,以下代码运行良好。
object[]Source=null;
Type basetype=Var.FieldType.GetElementType();
int l=somelength;
if (basetype.IsEquivalentTo(typeof(string))) Source = new string[l];
//repeat for all types
source=//run your Reflection here
var.SetValue(target,source);