在直接调用委托的情况下如何缓解 "Access to modified closure"

How to mitigate "Access to modified closure" in cases where the delegate is called directly

我的理解是 "Access to modified closure" 警告是为了警告我在委托可能被存储并稍后调用或在不同线程上调用时从委托访问局部变量,以便局部变量不存在在实际代码执行时实际上不可用。这当然是明智的。

但是,如果我正在创建一个我知道将在同一线程中立即调用的委托怎么办?则不需要警告。例如,警告在代码中生成:

delegate void Consume();

private void ConsumeConsume(Consume c)
{
    c();
}

public int Hello()
{
    int a = 0;

    ConsumeConsume(() => { a += 9; });

    a = 1;

    return a;
}

这里没有问题,因为 ConsumeConsume 总是立即调用该函数。有没有办法解决?有什么方法可以注释函数 ConsumeConsume 以指示将立即调用委托的 ReSharper?

有趣的是,当我将 ConsumeConsume(() => { a += 9; }); 行替换为:

new List<int>(new[] {1}).ForEach(i => { a += 9; });

做同样的事情,没有产生警告。这只是 ReSharper 的内置异常,还是我可以做类似的事情来指示立即调用委托?

我知道我可以禁用这些警告,但这不是我想要的结果。

使用 NuGet 安装 JetBrains.Annotations 包:https://www.nuget.org/packages/JetBrains.Annotations

InstantHandle 属性标记传入的委托。

private void ConsumeConsume([InstantHandle] Consume c)
{
    c();
}

来自InstantHandle的描述:

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.

来源:https://www.jetbrains.com/help/resharper/Reference__Code_Annotation_Attributes.html

如果您不想将整个包添加到您的项目中,只需自己添加属性就足够了,尽管在我看来这很老套。

namespace JetBrains.Annotations
{
    [AttributeUsage(AttributeTargets.Parameter)]
    public class InstantHandleAttribute : Attribute { }
}