静态变量实例和应用程序域,发生了什么? [英] Static Variable Instances and AppDomains, what is happening?
问题描述
我
public static class A
{
public static string ConnString;
}
[Serializable]
public class Test{
// Accesing A's field;
public string ConnString{get{return A.ConnString;}set{A.ConnString=value;}}
}
void Main()
{
A.ConnString = "InitialString"; // I set A.ConnString in the current domain
var newDomain = AppDomain.CreateDomain("DomNew");
Test TObj = newDomain.CreateInstanceAndUnwrap(typeof(Test).Assembly.FullName, typeof(Test).FullName) as Test ;
TObj.ConnString = "NewDomainString"; // It is supposed to set A.ConnString in the newDomain aka a different instance of A.ConnString
// Here it is supposed to print two different values
Console.WriteLine(A.ConnString); // "InitialString"
Console.WriteLine(TObj.ConnString); // "NewDomainString"
}
但是,没有!这两个WriteLines,打印出相同的价值NewDomainString!
为什么???
But NO! The two WriteLines, print out the same value "NewDomainString"! WHY???
此代码
TObj.ConnString = "NewDomainString"
应该更改新创建的域字符串,但似乎它们都指的是同一个实例!
is supposed to change the string in the newly created domain, but it seems they both refer to the same instance!
为什么,这里发生了什么?
Why, what is happening here?
推荐答案
有只有两个办法一类是从另一个AppDomain-可接触的是类 [Serializable接口]
,作为你的测试类中,另一种是如果该类从 MarshalByRefObject的继承。因为你的类是序列化的,是每一个跨AppDomain的调用创建它的一个副本。因此,测试
主AppDomain中得到,当你调用...
There are only two ways for a class to be accessible from another AppDomain- one is is the class is [Serializable]
, as your Test class is, the other is if the class inherits from MarshalByRefObject. Because your class is Serializable, a copy of it is created for every cross-AppDomain call. So the Test
that the main appdomain gets when you call...
Test TObj = newDomain.CreateInstanceAndUnwrap(typeof(Test).Assembly.FullName, typeof(Test).FullName) as Test;
其实并没有被在DomNew创建AppDomain-是本地的一个副本的测试实例为主的AppDomain,因此,从主的AppDomain引用了静态变量。
is actually not the Test instance that was created in the "DomNew" AppDomain- it is a copy local to the "main" AppDomain, and therefore references the static variables from the "main" AppDomain.
如果你想测试
来表现出的行为,你期望的那样,使之从MarshalByRefObject继承的,而不是被序列化。
If you want Test
to exhibit the behavior that you expect, make it inherit from MarshalByRefObject instead of being Serializable.
这篇关于静态变量实例和应用程序域,发生了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!