c# - 访问闭包中的变量

标签 c# closures resharper predicate

我知道在 SO 上有很多关于这个问题的话题,Eric Lippert 也有一篇很棒的帖子.我仍然不太确定以下代码中发生了什么以及 Resharper 警告的原因:

public class Class
{
  public string Id { get; set; }
}

public class GenericClass<T>
{
  public virtual bool Exists(Predicate<T> match)
  {
    return true;
  }
}

public class Main
{
  public void Test()
  {
    var list = new List<Class>();
    var list2 = new GenericClass<Class>();

    foreach (var item in list)
    {
      if (list2.Exists(o => o.Id == item.Id)) // access to variable in closure on item
    }
  }
}

这可以很容易地解决:

var localCopy = item;
if (list2.Exists(o => o.Id == localCopy.Id))

据我所知,在 exists 中创建的所有闭包在 localCopy 中都引用相同的实例,对吗?但这应该不是问题,因为 exists 是立即评估的,对吗?那么我哪里错了?

最佳答案

But this should not be an issue since the exists is evaluated instantly right?

是的,GenericClass.Exists 急切地计算 lambda,但 ReSharper 不知道。

所有 ReSharper 都知道您正在将闭包传递给另一个方法 - 该方法可能延迟执行 lambda,因此出现警告。


Is there any way to tell resharper that, for that method, there is no need for the warning?

查看文档,似乎您可以使用 InstantHandleAttribute 修饰谓词参数属性。

Tells code analysis engine if the parameter is completely handled when the invoked method is on stack. If the parameter is a delegate, indicates that delegate is executed while the method is executed. If the parameter is an enumerable, indicates that it is enumerated while the method is executed

请参阅此处了解如何安装 JetBrains 代码注释属性:Annotations in Source Code

关于c# - 访问闭包中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26840262/

相关文章:

c# - Microsoft.Web.Infrastructure 未构建到我的 TFS 构建服务器之一的 bin 目录中

c# - 将字节数组转换为带分隔符的字符串

javascript - 使用用户扩展 jQuery 插件默认选项

使用 IntelliJ IDEA 在 Groovy 中调试迭代(闭包)

c++ - 解决 size_t 声明中的歧义

c# - 如何强制 Visual Studio 在 https 中运行网站

c# - visual studio 2015 在构建时卡住,杀死 find.exe(三次)完成构建过程

python - 这个闭包有没有更 'pythonic'的写法?

.net - 断言不确定和忽略属性

resharper - 为什么 ReSharper Find Usages 命令会搜索 resx 文件?