在ReSharper的修改封警告 [英] modified closure warning in ReSharper

查看:189
本文介绍了在ReSharper的修改封警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有人能向我解释,坏事可以在这个code,这将导致ReSharper的给一个进入修改封警告发生什么:

 布尔结果=真;

的foreach(在keys.TakeWhile(密钥字符串键=>的结果))
{
    结果=结果和放大器;&安培;的containsKey(密钥);
}

返回结果;
 

即使code以上似乎是安全,可以在其他修改关闭情况下发生什么不好的事情?我经常看到这样的警告,使用LINQ查询的结果,而我往往会忽略它,因为我不知道什么可能出问题。 ReSharper的试图通过似乎并没有给我,比如第二个变量来解决这个问题它改变了的foreach 线以上:

 布尔RESULT1 =结果;
的foreach(字符串键keys.TakeWhile(键=> RESULT1))
 

更新:在一个侧面说明,显然是code表示整个块可以转换为下面的语句,因此不会修改封警告:

 返回keys.Aggregate(
    真正,
    (目前,键)=>当前和放大器;&安培;的containsKey(钥匙)
);
 

解决方案

当你修改结果变量,关闭(使用变量的拉姆达前$内p $ pssion)将拿起变化。

这频繁之际,一个意外的惊喜,以程序员谁不完全理解闭包,所以ReSharper的有一个警告吧。

通过做一个单独的 RESULT1 变量,仅在拉姆达EX pression使用,它会忽略任何更改,原来的结果变量。

在你的code,你是依靠封闭拿起改变原来的变量,这样它会知道什么时候停止。

顺便说一句,写你的功能,而不LINQ是这样的最简单的方法:

 的foreach(在钥匙串键){
    如果(的containsKey(密钥))
        返回true;
}
返回false;
 

使用LINQ,你可以简单地调用任何()

 返回keys.Any<字符串>(的containsKey);
 

I was hoping someone could explain to me what bad thing could happen in this code, which causes ReSharper to give an 'Access to modified closure' warning:

bool result = true;

foreach (string key in keys.TakeWhile(key => result))
{
    result = result && ContainsKey(key);
}

return result;

Even if the code above seems safe, what bad things could happen in other 'modified closure' instances? I often see this warning as a result of using LINQ queries, and I tend to ignore it because I don't know what could go wrong. ReSharper tries to fix the problem by making a second variable that seems pointless to me, e.g. it changes the foreach line above to:

bool result1 = result;
foreach (string key in keys.TakeWhile(key => result1))

Update: on a side note, apparently that whole chunk of code can be converted to the following statement, which causes no modified closure warnings:

return keys.Aggregate(
    true,
    (current, key) => current && ContainsKey(key)
);

解决方案

When you modify the result variable, the closure (the use of the variable inside the lambda expression) will pick up the change.

This frequently comes as an unexpected surprise to programmers who don't fully understand closures, so Resharper has a warning for it.

By making a separate result1 variable which is only used in the lambda expression, it will ignore any subsequent changes to the original result variable.

In your code, you're relying on the closure picking up the changes to the original variable so that it will know when to stop.

By the way, the simplest way to write your function without LINQ is like this:

foreach (string key in keys) {
    if (ContainsKey(key))
        return true;   
}
return false;

Using LINQ, you can simply call Any():

return keys.Any<string>(ContainsKey);

这篇关于在ReSharper的修改封警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆