使用List <Func <T,object >>时,索引超出了数组的范围

Hos*_*Rad 6 c# func

我有一个这样的课:

class MyClass { public object[] Values; }
Run Code Online (Sandbox Code Playgroud)

在其他地方我正在使用它:

MyClass myInstance = new MyClass() {Values = new object[]{"S", 5, true}};

List<Func<MyClass, object>> maps = new List<Func<MyClass, object>>();

for (int i = 0; i < myInstance.Values.Length ; i++)
{
    maps.Add(obj => obj.Values[i]);
}

var result = maps[0](myInstance); //Exception: Index outside the bounds of the array
Run Code Online (Sandbox Code Playgroud)

我以为它会返回S,但它会抛出异常.知道发生了什么事吗?

Mar*_*zek 8

要查看正在发生的事情,请将您的lambda更改为maps.Add(obj => i);.

随着这种变化result将是3,这就是为什么你得到IndexOutOfBoundException例外:你正试图得到myInstance[3]哪些不存在.

要使其工作,请int在循环中添加局部变量,并将其用作索引而不是循环计数器i:

for (int i = 0; i < myInstance.Values.Length; i++)
{
    int j = i;
    maps.Add(obj => obj.Values[j]);
}
Run Code Online (Sandbox Code Playgroud)