Type.MakeArrayType 方法
2013/3/11
返回一个表示当前类型的一维数组(下限为零)的 Type 对象。
程序集: mscorlib(位于 mscorlib.dll 中)
| 异常 | 条件 |
|---|---|
| NotSupportedException | 基类不支持所调用的方法。派生类必须提供实现。 |
| TypeLoadException | 当前类型是 ByRef 类型。即 Type.IsByRef 返回 true。 |
MakeArrayType 方法提供了一种生成元素类型在运行时计算的数组类型的方式。
注意 公共语言运行时对向量(即始终从零开始的一维数组)和多维数组进行了区分。向量始终只有一个维度,它与恰好只有一个维度的多维数组不同。此方法重载只能用来创建向量类型,而且是创建向量类型的唯一方法。请使用 MakeArrayType(Int32) 方法重载来创建多维数组类型。
下面的代码示例为 Test 类创建数组、ref(在 Visual Basic 中为 ByRef)和指针类型。
注意: |
|---|
要运行此示例,请参见生成具有静态 Windows Phone TextBlock 控件的示例。 |
using System; using System.Reflection; public class Example { public static void Demo(System.Windows.Controls.TextBlock outputBlock) { // Create a Type object that represents a one-dimensional // array of Example objects. Type t = typeof(Example).MakeArrayType(); outputBlock.Text += String.Format("\r\nArray of Example: {0}\n", t); // Create a Type object that represents a two-dimensional // array of Example objects. t = typeof(Example).MakeArrayType(2); outputBlock.Text += String.Format("\r\nTwo-dimensional array of Example: {0}\n", t); // Demonstrate an exception when an invalid array rank is // specified. try { t = typeof(Example).MakeArrayType(-1); } catch (Exception ex) { outputBlock.Text += String.Format("\r\n{0}\n", ex); } // Create a Type object that represents a ByRef parameter // of type Example. t = typeof(Example).MakeByRefType(); outputBlock.Text += String.Format("\r\nByRef Example: {0}\n", t); // Get a Type object representing the Example class, a // MethodInfo representing the "Test" method, a ParameterInfo // representing the parameter of type Example, and finally // a Type object representing the type of this ByRef parameter. // Compare this Type object with the Type object created using // MakeByRefType. Type t2 = typeof(Example); MethodInfo mi = t2.GetMethod("Test"); ParameterInfo pi = mi.GetParameters()[0]; Type pt = pi.ParameterType; outputBlock.Text += String.Format("Are the ByRef types equal? {0}\n", (t == pt)); // Create a Type object that represents a pointer to an // Example object. t = typeof(Example).MakePointerType(); outputBlock.Text += String.Format("\r\nPointer to Example: {0}\n", t); } // A sample method with a ByRef parameter. // public void Test(ref Example e) { } } /* This example produces output similar to the following: Array of Example: Example[] Two-dimensional array of Example: Example[,] System.IndexOutOfRangeException: Index was outside the bounds of the array. at System.RuntimeType.MakeArrayType(Int32 rank) in c:\vbl\ndp\clr\src\BCL\System\RtType.cs:line 2999 at Example.Demo(TextBlock outputBlock) ByRef Example: Example& Are the ByRef types equal? True Pointer to Example: Example* */
注意: