[英]Convert C# Type to the type of an array of type
I need the Type of an Array of n elements of a type given in a Type variable. 我需要类型变量中给定类型的n个元素的数组的类型。 I'm getting round the problem like this:
我正在解决这样的问题:
Type foo;
int n;
Type newType=(Array.CreateInstance(foo,n)).GetType();
This works but it does mean I'm actually creating an unused array just to get it's type. 这可行,但这确实意味着我实际上是在创建一个未使用的数组以获取其类型。 I'm sure there must be a better way!
我相信一定有更好的方法!
You can use Type.MakeArrayType()
: 您可以使用
Type.MakeArrayType()
:
Type foo = typeof(Foo);
Type arrayType = foo.MakeArrayType();
This returns the Type
of an one-dimensional array of Foo
. 这将返回
Foo
的一维数组的Type
。 The length
of the array is not relevant for the type. 数组的
length
与类型无关。
For multi-dimensional arrays you can use this overload 对于多维数组,可以使用此重载
Type foo = typeof(Foo);
int dimensions = 5;
Type arrayType = foo.MakeArrayType(dimensions);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.