在.Net中是一个公共静态变量的"静态",仅限于AppDomain或整个过程?

Har*_*aka 5 .net variables static scope appdomain

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

Dar*_*rov 10

这个示例证明了每个应用程序域:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)