Skip to main content
 首页 » 编程设计

c#之访问闭包中的变量

2024年02月06日14qlqwjy

我知道在 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