如何使用给定的 ElementType 创建 Array 类型的实例? [英] How do I create an instance of the Array type with a given ElementType?
本文介绍了如何使用给定的 ElementType 创建 Array 类型的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何创建一个类型对象来表示具有给定元素类型的数组的类型?
How do I create a type object that represents the type of an array with a given element type?
Type t = MakeArrayType(elementType); // How?
这样
Assert(t.GetElementType() == elementType);
我可以为我请求的数组创建一个虚拟的实例,然后从那里获取类型.但是我想知道有没有办法不用先创建实例就可以得到类型?
I can create a dummy instance of my requested array and then get the type from there. But I wonder if there is a way to get the type without creating the instance first?
object myArrayInstance = Array.CreateInstance(elementType, 0);
Type t = myArrayInstance.GetType(); // This is the desired type.
推荐答案
如果 t
引用一个 Type
,则 t.GetType()
显然是 typeof(Type)
或子类型 - 而不是 typeof(Array)
.
If t
refers to a Type
, then t.GetType()
will obviously be typeof(Type)
or a subtype - not typeof(Array)
.
但是,我怀疑您想要 Type.MakeArrayType
:
However, I suspect you want Type.MakeArrayType
:
Type arrayType = elementType.MakeArrayType();
这篇关于如何使用给定的 ElementType 创建 Array 类型的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文