How do I create an instance of the Array type with

2019-08-27 21:59发布

问题:

How do I create a type object that represents the type of an array with a given element type?

Type t = MakeArrayType(elementType);  // How?

Such that

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.

回答1:

If t refers to a Type, then t.GetType() will obviously be typeof(Type) or a subtype - not typeof(Array).

However, I suspect you want Type.MakeArrayType:

Type arrayType = elementType.MakeArrayType();