C#静态变量 - 范围和持久性 [英] C# Static variables - scope and persistence

查看:206
本文介绍了C#静态变量 - 范围和持久性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是做了一个小实验:

I just did a little experiment:

public abstract class MyClass
{
  private static int myInt = 0;

  public static int Foo()
  {
    return myInt;
  }

  public static int Foo(int n)
  {
    myInt = n;
    return bar();
  }

  private static int bar()
  {
    return myInt;
  }
}

然后我跑:

MessageBox.Show(MyClass.Foo().ToString());
MessageBox.Show(MyClass.Foo(3).ToString());
MessageBox.Show(MyClass.Foo().ToString());
MessageBox.Show(MyClass.Foo(10).ToString());
MessageBox.Show(MyClass.Foo().ToString());

我希望的结果是0,3,0,10,0。

The results I expected were 0, 3, 0, 10, 0.

要我惊讶的是,我得到0,3,3,10,10。

To my surprise, I got 0, 3, 3, 10, 10.

这些改变持续多久呢?程序执行的时间?该函数调用的静态方法的时间?

How long do these changes persist for? The duration of the program execution? The duration of the function calling the static method?

推荐答案

他们会持续的的AppDomain 。做静态变量的变化是整个的方法可见。

They will persist for the duration of AppDomain. Changes done to static variable are visible across methods.

MSDN:

如果局部变量与静态关键字声明,其寿命比在它被声明的过程的执行时间长。如果程序是一个模块内,静态变量生存,只要你的应用程序仍继续运行。

If a local variable is declared with the Static keyword, its lifetime is longer than the execution time of the procedure in which it is declared. If the procedure is inside a module, the static variable survives as long as your application continues running.

请参阅下面的更多细节:

See following for more details:

  • MSDN: Static Variable
  • MSDN: Variable Lifetime

这篇关于C#静态变量 - 范围和持久性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆