静态变量实例和 AppDomains,发生了什么? [英] Static Variable Instances and AppDomains, what is happening?

查看:31
本文介绍了静态变量实例和 AppDomains,发生了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

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"
}

但是不!两条WriteLine,打印出相同的值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],如您的 Test 类是,另一个是该类是否继承自 MarshalByRefObject.因为您的类是可序列化的,所以每次跨 AppDomain 调用都会创建一个它的副本.所以当你调用时主应用程序域得到的 Test...

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 中创建的Test 实例——它是main"AppDomain 的本地副本,因此引用main"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.

如果您希望 Test 表现出您期望的行为,请使其继承自 MarshalByRefObject 而不是可序列化.

If you want Test to exhibit the behavior that you expect, make it inherit from MarshalByRefObject instead of being Serializable.

这篇关于静态变量实例和 AppDomains,发生了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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