c# - 在 C# 中将 IList 转换为数组

标签 c# arrays ilist .net

我想将 IList 转换为数组: 请看我的代码:

IList list = new ArrayList();
list.Add(1);
Array array = new Array[list.Count];
list.CopyTo(array, 0);

为什么我得到 System.InvalidCastException:源数组中的至少一个元素无法转换为目标数组类型?假设我不能使用 ArrayList 作为 list 变量的类型,如何解决这个问题?

更新 1:我使用 .NET 1.1。所以我不能使用泛型、Linq 等等。我只想接收最常见情况的结果 - 以整数为例,我需要这段代码适用于所有类型,所以我在这里使用 Array (也许我使用 Array 是错误的,但我需要,再次,常见情况)。

最佳答案

您正在创建 Array 的数组 值(value)观。 1 是 int ,不是 Array .你应该:

IList list = new ArrayList();
list.Add(1);
Array array = new int[list.Count];
list.CopyTo(array, 0);

或者,理想情况下,不要使用非泛型类型开始...使用 List 而不是 ArrayList , IList<T>而不是 IList等等

编辑:请注意,第三行很容易是:

Array array = new object[list.Count];

相反。

关于c# - 在 C# 中将 IList 转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9507002/

相关文章:

c# - 从 Azure Management Fluent 创建 Azure 存储帐户时如何指定 CORS 设置

c# - GridView 页脚不起作用

python - 来自 netcdf 的 Xarray 数据数组返回大于输入的 numpy 网格数组

java - Arrays.asList(an_array).contains(an_integer) 总是 false。为什么?

c# - IList.Add() 覆盖现有数据

c# - 有关在 .Net 中编写 XML 文件的问题吗?

c# - 使用 OAuth2 在 Office 365 中进行 IMAP 身份验证

c - 在 C 编程中检索数组值。我该如何修复这些错误?

c# - 如何对 iList 进行排序(使用或不使用 linq)