繁体   English   中英

ReSharper / Linq错误:访问修改后的闭包

[英]ReSharper/Linq error: Access to modified closure

在我的ASP MVC 3网站上的验证.cs文件中,我试图对数据库进行快速检查,以查看是否存在用户输入的代理ID号。但是,ReSharper在agentId变量下标识了一个错误,该错误是读取Access to modified closure 我不确定此错误是什么意思,或者此语句有何错误。

这是我们编写到Validation程序中的辅助方法。 它不是在循环上设置的,而是在五个位置之一中检测到代理ID时从上方调用。

这是调用StatValidation的代码

if (String.IsNullOrEmpty(agt.AgencyId1))
{
   _sb.Append("One Agency Id is required; ");
}
else
{
    StatValidation(agt.AgencyCompany1, 
              agt.AgencyId1.Trim(), agt.AgencyIdType1, 1);
}

//Conditionally validate remaining Agent IDs
if (!String.IsNullOrWhiteSpace(agt.AgencyId2) || 
    !String.IsNullOrWhiteSpace(agt.AgencyCompany2))
{
    StatValidation(agt.AgencyCompany2, agt.AgencyId2, agt.AgencyIdType1, 2);
}

这是方法标题和给出错误的代码行

private static void StatValidation(string company, 
      string agentId, string idType, int i)
{
   AgentResources db = new AgentResources();
   // ReSharper is highlighting 'agentId' with the error 
   // 'Access to modified closure'
   var check = db.SNumberToAgentId.Where(x => x.AgentId.Equals(agentId));

   if (check == null) _sb.Append("Agent ID not found; ");

Access to modified closure消息表示您的表达式正在捕获一个变量,该变量在捕获后确实/可能会更改其值。 考虑以下

var myList = new List<Action>();

for(var i = 0; i < 5; ++i)
{
    myList.Add(() => Console.WriteLine(i));
}

foreach(var action in myList)
{
    action();
}

这将打印5 5次数字,因为i是被表达式捕获的,而不是i的值。 由于i的值在循环的每次迭代中都会更改,因此每次操作都会在i每次执行时更改其值,由于它是循环的边界条件,因此最终降为5

至于您要给出的特定示例,由于要懒惰地评估Where (同样,它永远不会为null,因此它只是一个枚举,第一次尝试时无法移至下一条记录),如果您要评估通过在if语句之后再次枚举进行check ,将评估迭代时agentId当前值,而不必评估参数中的原始值。

要解决此问题,请更改:

var check = db.SNumberToAgentId.Where(x => x.AgentId.Equals(agentId));

对此:

var check = db.SNumberToAgentId.Where(x => x.AgentId.Equals(agentId)).ToList();

这将强制一次对Where迭代器进行一次评估,并在该行上使用agentId当前值,如果agentId在方法中稍后更改,则该更改将不会影响check的值。

另外,更改:

if (check == null) _sb.Append("Agent ID not found; ");

对此:

if (check.Count == 0) _sb.Append("Agent ID not found; ");

使您的支票有效

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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