我有一个这样的课:
class MyClass { public object[] Values; }
我正在其他地方使用它:
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
我以为它会返回S
,但是会抛出异常。知道发生了什么吗?
要查看发生了什么,请将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]);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句