我有一个这样的课:
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);.
有了这个改变结果将是3,这就是你得到IndexOutOfBoundException异常的原因:你试图获得不存在的myInstance [3].
为了使它工作,在循环中添加局部int变量并将其用作索引而不是循环计数器i:
for (int i = 0; i < myInstance.Values.Length; i++) { int j = i; maps.Add(obj => obj.Values[j]); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。