简体   繁体   English

通过反射将对象[]转换为类型[]

[英]Cast Object[] to Type[] via Reflection

Goal 目标

I have an object[]Source,object Target, and FieldInfo Var (Var.FieldType.IsArray is true). 我有一个object [] Source,object Target和FieldInfo Var(Var.FieldType.IsArray为true)。 I want to run Var.SetValue(Target,Source). 我想运行Var.SetValue(Target,Source)。 However, I cannot convert "object[]" -> "anotherType[]" 但是,我不能转换“ object []”->“ anotherType []”

Sample Run 样品运行

object[]Source=new object[2]{"Hello","World"};
Var.SetValue(Target,Source); //Cannot Convert "object[]"->"string[]"

[note: I want to be able to use ints, doubles, floats, etc. Otherwise, this problem would be trivially easy] [注意:我希望能够使用整数,双精度数,浮点数等。否则,此问题将非常容易实现]

Research 研究

Use Var: Cannot use because cannot create var arrays 使用变量:无法使用,因为无法创建变量数组

Use Generics: 使用泛型:

This works for 这适用于

myField.SetValue(target,GenericCastArray<string>(source));

However, it does not work for 但是,它不适用于

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/ * returns null reference exception, I think at this.GetType() * http://social.msdn.microsoft.com/Forums/zh-CN/csharplanguage/thread/fe14d396-bc35-4f98-851d-ce3c8663cd79/ *返回空引用异常,我认为在this.GetType()

EDIT: Meh Solution Based on the comments, it is impossible to convert from object[] to string[]. 编辑:Meh解决方案基于注释,不可能从object []转换为string []。 However, the following code works adequately well. 但是,以下代码可以正常运行。

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); 

It is not possible to cast Array of one type to Array of another type (ie object[] to string[] ) because these are different non compatible types. 无法将一种类型的Array强制转换为另一种类型的Array(即object[]string[] ),因为它们是不同的不兼容类型。 Reflection will not help to cast either. 反思也无济于事。

To convert you will always need to create some sort of copy of the array either directly or by creating IEnumerable<DestinationType> via one of LINQ conversion functions. 要进行转换,您将始终需要直接创建数组的某种副本,或者通过LINQ转换函数之一创建IEnumerable<DestinationType>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM