C#中是否存在一个关键字,使局部变量在多个调用中保持不变?

C#中是否存在一个关键字,使局部变量在多个调用中保持不变?,c#,c#-4.0,C#,C# 4.0,也就是说,在C中,我们可以定义如下函数: func(){ static int foo = 1; foo++; return foo; } 每次调用时,它都会返回一个更高的数字。 在C#中是否有一个等价的关键字?不,在C#中没有这样的东西。要在多个方法调用中持久化的所有状态都必须位于字段中(实例或静态) 除了。。。如果在lambda表达式或类似的东西中捕获变量。例如: public Func<int> GetCounter() { int c

也就是说,在C中,我们可以定义如下函数:

func(){   
  static int foo = 1;   
  foo++;  
  return foo;  
}
每次调用时,它都会返回一个更高的数字。
在C#中是否有一个等价的关键字?

不,在C#中没有这样的东西。要在多个方法调用中持久化的所有状态都必须位于字段中(实例或静态)

除了。。。如果在lambda表达式或类似的东西中捕获变量。例如:

public Func<int> GetCounter()
{
    int count = 0;

    return () => count++;
}
public Func GetCounter()
{
整数计数=0;
return()=>count++;
}
现在您可以使用:

Func<int> counter = GetCounter();
Console.WriteLine(counter()); // Prints 0
Console.WriteLine(counter()); // Prints 1
Console.WriteLine(counter()); // Prints 2
Console.WriteLine(counter()); // Prints 3
Func counter=GetCounter();
Console.WriteLine(counter());//打印0
Console.WriteLine(counter());//印刷品1
Console.WriteLine(counter());//印刷品2
Console.WriteLine(counter());//印刷品3
当然,现在您只调用了一次
GetCounter()
,但是“局部变量”肯定已经超出了您预期的生命周期


这可能对你有用,也可能没用——这取决于你在做什么。但大多数时候,对象的状态在普通字段中确实有意义。

您必须为该方法所在的类创建一个静态或实例成员变量。

C是在线程还不存在时发明的。Visual Basic也是如此,他们必须在vb.net中实现它。它需要生成大量代码来保证线程和异常安全。使用闭包来模拟静态局部变量是否构成恶意代码?
public class Foo
{
    static int _bar = 1;

    public int Bar()
    {
        return ++_bar;
    }
}