【问题标题】:In .Net is the 'Staticness' of a public static variable limited to an AppDomain or the whole process?在 .Net 中,公共静态变量的“静态”是否仅限于 AppDomain 或整个过程?
【发布时间】:2011-09-27 13:50:34
【问题描述】:

是为进程中的每个 AppDomain 创建一个公共静态变量的副本,还是仅为整个进程创建一个副本?换句话说,如果我从一个 AppDomain 中更改静态变量的值,是否会影响同一进程中另一个 AppDomain 中相同静态变量的值?

【问题讨论】:

    标签: .net variables static scope appdomain


    【解决方案1】:

    正如本例所证明的,它是每个应用程序域:

    public class Foo
    {
        public static string Bar { get; set; }
    }
    
    public class Test
    {
        public Test()
        {
            Console.WriteLine("Second AppDomain: {0}", Foo.Bar);
        }
    }
    
    class Program
    {
        static void Main()
        {
            // Set some value in the main appdomain
            Foo.Bar = "bar";
            Console.WriteLine("Main AppDomain: {0}", Foo.Bar);
    
            // create a second domain
            var domain = AppDomain.CreateDomain("SecondAppDomain");
    
            // instantiate the Test class in the second domain
            // the constructor of the Test class will print the value
            // of Foo.Bar inside this second domain and it will be null
            domain.CreateInstance(Assembly.GetExecutingAssembly().FullName, "Test");
        }
    }
    

    【讨论】:

    • 当我尝试运行示例程序时,我得到一个 TypeLoadException 消息无法从程序集 'ConsoleApplication1,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null 加载类型 'Test' '。 HResult 是 80131522。
    【解决方案2】:

    仅限于AppDomain,也就是说,变量作为单独的值存在于每个AppDomain中。

    【讨论】:

      猜你喜欢
      • 2011-07-12
      • 2010-10-19
      • 1970-01-01
      • 2011-09-23
      • 1970-01-01
      • 2015-03-19
      • 2016-10-25
      • 1970-01-01
      相关资源
      最近更新 更多