简体   繁体   中英

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.

How can that be?

The CustomArray type is not an array, it's a custom type with an indexed property.

The ForEach<T> method expects an array with elements of type T , and it didn't get one.

Just because you can use the same operator ( [] ) on both and array and an indexed property, does not mean they are the same thing. For example, arrays are sequential by nature, meaning that if a[0] and a[2] exist, that implies the existence of 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:

var arr = new MyType[10];

and now you have an array that can house 10 MyType objects. Initially the values in any of the array's slots is null (assuming MyType is a class).

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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