简体   繁体   English

Array.ForEach无法从使用情况推断数组元素类型

[英]Array.ForEach cannot infer array element type from usage

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));

This will not compile saying: 这不会编译说:

The type arguments for method void System.Array.ForEach(T[], Action) cannot be inferred from the usage. 无法从用法中推断方法void System.Array.ForEach(T [],Action)的类型参数。

How can that be? 怎么可能?

The CustomArray type is not an array, it's a custom type with an indexed property. CustomArray类型不是数组,而是具有索引属性的自定义类型。

The ForEach<T> method expects an array with elements of type T , and it didn't get one. ForEach<T>方法期望一个数组,其元素类型为T ,但没有得到一个。

Just because you can use the same operator ( [] ) on both and array and an indexed property, does not mean they are the same thing. 仅仅因为您可以在array和一个索引属性上使用相同的运算符( [] ),并不意味着它们是同一回事。 For example, arrays are sequential by nature, meaning that if a[0] and a[2] exist, that implies the existence of a[1] . 例如,数组本质上是顺序的,这意味着如果a[0]a[2]存在,则意味着存在a[1] Indexed properties, on the other hand, are more like methods that get a parameter, and they are free to do with it whatever they want. 另一方面,索引属性更像是获取参数的方法,并且可以随心所欲地随意处理它。


If you want to declare an array of MyType objects, you do not need to do any special declarations, you can just do: 如果要声明MyType对象的数组,则无需执行任何特殊的声明,只需执行以下操作:

var arr = new MyType[10];

and now you have an array that can house 10 MyType objects. 现在您有了一个可以容纳10个MyType对象的数组。 Initially the values in any of the array's slots is null (assuming MyType is a class). 最初,任何数组插槽中的nullnull (假设MyType是一个类)。

Also I would steer clear of the Array.ForEach method, I'd prefer using a simple for or foreach loop, or maybe, in this particular case, the List.AddRange method: 另外,我将避免使用Array.ForEach方法,我更喜欢使用简单的for或foreach循环,或者在这种特殊情况下,使用List.AddRange方法:

intList.AddRange(arr.Select(x=> x.MyProperty));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM