I need the Type of an Array of n elements of a type given in a Type variable. 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 foo = typeof(Foo);
Type arrayType = foo.MakeArrayType();
This returns the Type
of an one-dimensional array of Foo
. The length
of the array is not relevant for the type.
For multi-dimensional arrays you can use this overload
Type foo = typeof(Foo);
int dimensions = 5;
Type arrayType = foo.MakeArrayType(dimensions);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.