我想从 ArrayList 中的值范围创建一个数组,但收到错误“源数组中的至少一个元素无法转换为目标数组类型”。
为什么以下会失败,你会怎么做?
int[] ints = new int[] { 1, 2, 3 };
ArrayList list = ArrayList.Adapter(ints);
int[] mints = (int[])list.GetRange(0, 2).ToArray(typeof(int));
如果您可以使用数组,也许只是Array.Copy
:
int[] ints = new int[] { 1, 2, 3 };
int[] mints = new int[2];
Array.Copy(ints, 0, mints, 0, 2);
或者,看起来您必须创建一个数组并循环/强制转换。
(对于信息,它在 2.0 上“按原样”工作正常 - 尽管你会List<int>
改用)
这在 DotNet 2.0 中运行良好,所以我建议从比较反汇编的框架代码开始,看看有什么区别。
在 2.0 中,调用 ArrayList.Adapter() 返回一个 ArrayList.IListWrapper(它继承自 ArrayList),它简单地包装了一个 IList(在您的情况下,是一个 int[] 类型的数组)。在 IListWrapper 上调用 ToArray 会在基础数组上调用 IList.CopyTo。
显然这必须在 1.1 中以不同的方式实现,因为它在 2.0 中的设置方式,它不会失败。
通常,这应该可以工作:
(int[])list.GetRange(0, 2).ToArray(typeof(int));
因为 GetRange 只是返回一个新的 ArrayList。
你确定你的 ArrayList 只包含整数,没有别的吗?
我无法在 .NET 1.1 中对其进行测试,但我认为: - 您的数组列表包含其他类型的元素,然后是 int。- ArrayList.Adapter 方法是问题的始作俑者。
另外,为什么不像这样初始化 ArrayList:
ArrayList l = new ArrayList ( new int[] {0, 1, 2, 3, 4, 5});
?