public class MyType
{
public int SomeProperty { get; set; }
}
public class CustomArray
{
public MyType this[int index]
{
//some code
}
}
var intList = new List<int>();
var arr = new CustomArray();
Array.ForEach(arr, x => intList.Add(x.MyProperty));
这不会编译说:
The type arguments for method void System.Array.ForEach(T[], Action) cannot be inferred from the usage.
这怎么可能?
最佳答案
CustomArray
类型不是数组,它是具有索引属性的自定义类型。
ForEach<T>
方法需要一个元素类型为 T
的数组, 但它没有得到一个。
仅仅因为您可以对数组和索引属性使用相同的运算符 ( []
),并不意味着它们是同一回事。例如,数组本质上是顺序的,这意味着如果 a[0]
和 a[2]
存在,这意味着 a[1]
的存在.另一方面,索引属性更像是获取参数的方法,它们可以随心所欲地使用它。
如果你想声明一个MyType
的数组对象,你不需要做任何特殊的声明,你可以这样做:
var arr = new MyType[10];
现在你有一个可以容纳 10 个 MyType
的数组对象。最初,任何数组槽中的值都是 null
(假设 MyType
是一个类)。
另外我会避开 Array.ForEach
方法,我更喜欢使用简单的 for 或 foreach 循环,或者在这种特殊情况下,可能使用 List.AddRange
方法:
intList.AddRange(arr.Select(x=> x.MyProperty));
关于c# - Array.ForEach 无法从用法推断数组元素类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18741616/