虽然这可能是一个奇怪的需求,但我需要在 .Net 中创建一个下限 > 0 的数组。起初似乎可以通过以下方式实现:
Array.CreateInstance(typeof(Object), new int[] {2}, new int[] {9});
生成所需的结果(一个下边界设置为9的对象数组)。但是,创建的数组实例不能再传递给期望Object[]
的其他方法,否则会出现错误,如下所示:
System.Object[*]
无法强制转换为 System.Object[]
。这些数组类型之间的区别是什么,我该如何克服这个问题?
编辑:测试代码 =
Object x = Array.CreateInstance(typeof(Object), new int[] {2}, new int[] {9});
Object[] y = (Object[])x;
该操作失败,提示信息为:“无法将类型为 'System.Object[*]' 的对象强制转换为类型 'System.Object[]'。”
我还想指出的是,当使用多个维度时,这种方法确实有效:
Object x = Array.CreateInstance(typeof(Object), new int[] {2,2}, new int[] {9,9});
Object[,] y = (Object[,])x;
这很好用。