我正在进行以下集合初始化:
Int32[,] v1 = new Int32[2, 2] { { 1, 2 }, { 3, 4 } };
IEnumerable<IEnumerable<Int32>> v2 = new List<List<Int32>> { { 2, 3 }, { 3, 4 } };
在第二行我得到错误:
No overload for method 'Add' takes 2 arguments
有没有办法使用最新的 C# 版本来创建 IEnumerable<IEnumerable<Int32>>
不添加 new List<Int32>
对于主集合中的每个项目?
IEnumerable<IEnumerable<Int32>> v2 = new List<List<Int32>> {
new List<Int32> { 2, 3 },
new List<Int32> { 3, 4 }
};
最佳答案
无需围绕 List<List<T>>
编写包装器!
集合初始值设定项只是调用名为 Add
的方法的语法糖由对象声明,List<T>
没有声明 Add
采用 2 个参数(或 1 个以上的任意数量的参数)的方法。
但是,集合初始值设定项还将调用名为 Add
的扩展方法.这意味着我们可以这样写:
public static class ListExtensions
{
public static void Add<T>(this List<List<T>> list, params T[] items)
{
list.Add(new List<T>(items));
}
}
然后我们可以这样写:
IEnumerable<IEnumerable<int>> collection = new List<List<int>>()
{
{ 1, 2 },
{ 3, 4 },
};
值得注意的是,这种 Add
方法只能作为扩展方法添加——List<T>
是不可能的自己声明。这样做的原因是只有当列表包含其他列表时才有意义,并且无法定义仅适用于某些类型列表的实例方法。但是,您可以在扩展方法上添加各种类似的限制。您可以在 List<T>
上编写扩展方法仅在 T
时适用是一个类,或者确实只有当T
是另一个列表!
关于c# - 如何将List<List<Int32>>的初始化简化为IEnumerable<IEnumerable<Int32>>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67518489/