转换对象数组到另一个使用数组类型的反思 [英] Convert Object Array to another type array using Reflection
问题描述
我有一个对象数组,我想将其转换为特定类型的数组。我必须把它转换成我在运行时获取类型。但我有做实际的转换问题。
如果我用的是Convert.ChangeType,我得到的对象必须实现IConvertible误差
该Array.ConvertAll是基于模板,并要求我通过目的地类型作为一个模板,我只知道在运行时。我甚至试图做使用反射调用此方法,但我不能通拉姆达前pression作为参数传递给MethodInfo.Invoke方法。
任何想法?
右键我有不工作的情况如下:
键入的ConvertTo = GetFinalType();
[对象] objArr = GetObjectArray();
VAR ARR = Array.ConvertAll(objArr,ELEM => Convert.ChangeType(ELEM,的ConvertTo));
您是否尝试过这个?
VAR finalType = GetFinalType();
变种objArr = GetObjectArray();
VAR ARR = Array.CreateInstance(finalType,objArr.Length);
Array.Copy(objArr,编曲,objArr.Length);
这是未经测试,但它应该工作。这是更紧凑,并没有(真正)使用反射。
-Doug
I have an object array and I want to convert it to a specific type array. I have the type to convert it into which I get at run time. But I am having a problem doing the actual conversion.
If I use the Convert.ChangeType, I get the error that Object must implement IConvertible
The Array.ConvertAll is template based and requires that I pass the destination type as a template which I only know at run time. I even tried to do use reflection to call this method but I cannot pass the lambda expression as an argument to the MethodInfo.Invoke method.
Any Ideas?
Right I have the following which is not working:
Type convertTo = GetFinalType();
Object[] objArr = GetObjectArray();
var arr = Array.ConvertAll(objArr,elem=> Convert.ChangeType(elem,convertTo));
Have you tried this?
var finalType = GetFinalType();
var objArr = GetObjectArray();
var arr = Array.CreateInstance(finalType, objArr.Length);
Array.Copy(objArr, arr, objArr.Length);
That's untested, but it should work. It's more compact and doesn't (really) use reflection.
-Doug
这篇关于转换对象数组到另一个使用数组类型的反思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!