c# – 使用List>时索引超出了数组的范围
发布时间:2020-12-15 04:30:40 所属栏目:百科 来源:网络整理
导读:我有一个这样的课: class MyClass { public object[] Values; } 在其他地方我正在使用它: MyClass myInstance = new MyClass() {Values = new object[]{"S",5,true}};ListFuncMyClass,object maps = new ListFuncMyClass,object();for (int i = 0; i myIns
我有一个这样的课:
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]); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |