C# 什么时候变量是闭包的一部分?

C# 什么时候变量是闭包的一部分?,c#,C#,假设我想创建一个匿名getter函数,该函数将返回成员变量foo的当前值。我可以这样写: Func<int> myFunction = delegate() { return foo; }; Func myFunction=delegate(){return foo;}; 但是假设我想要一个函数,它接受foo的值,将该值绑定到它的闭包中,然后每次调用它时都返回该值。我会写同样的东西: Func<int> myFunction = delegate() { return

假设我想创建一个匿名getter函数,该函数将返回成员变量foo的当前值。我可以这样写:

Func<int> myFunction = delegate() { return foo; };
Func myFunction=delegate(){return foo;};
但是假设我想要一个函数,它接受foo的值,将该值绑定到它的闭包中,然后每次调用它时都返回该值。我会写同样的东西:

Func<int> myFunction = delegate() { return foo; };
Func myFunction=delegate(){return foo;};

C#编译器如何区分这两种差异?有没有办法更具体地询问您想要什么?

匿名函数总是使用闭包

无法仅捕获变量的值

如果您不想让函数看到变量的更改,您可以创建一个单独的临时变量,并在函数中使用它,

看看这一点,特别是修改了闭包“bug”。他在解释这件事上比我读过的任何人都做得好

@SLaks是正确的,但是不能捕获变量的值。

“匿名函数总是使用闭包”或者它们关闭引用的任何变量。可以使用工厂方法正确地确定这些引用变量的范围,以便在创建
Func
时,
Func
返回
foo
的值。以下面的例子为例

private static Func<int> CreateFooFunc(int scopedFoo)
{
    return () => scopedFoo;
    //FYI, the line above is more concise version of line below
    //return () => { return scopedFoo; };
    //which is a more concise version of line below
    //return delegate() { return scopedFoo; };
}
请记住,如果
foo
本身的值是可变的(例如POCO),那么您必须复制它或
CreateFooFunc
中的某些内容才能获得相同的效果

private Func<int> CreateFooFunc()
{
    var scopedFoo = foo;
    return () => scopedFoo;
}
private Func<int> CreateFooFunc()
{
    return CreateFooFunc(foo)
}
Func<int> myFunction = CreateFooFunc(foo);