今天看CLR via C#,看到上面说,同一个类型会在不同应用程序域中存在多个映像,于是写了一段代码证明一下这个情况。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace RemotingTest
{
class Program
{
static void Main(string[] args)
{
AppDomain ad = AppDomain.CreateDomain("AppDomain2");
RemotingObj ro = ad.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, "RemotingTest.RemotingObj") as RemotingObj;//ro是本地的一个透明代理,指向新创建应用程序域中的对象
Console.WriteLine(ro.IndexOf("Michael Jackson", "Jack"));//到这里远程对象一定已经创建了,但是RemotingObj.Flag仍然为0,说明本应用程序域中的Type对象没有被设置,设定的是ad中的typeof(RemotingObj)
bool flag = System.Runtime.Remoting.RemotingServices.IsTransparentProxy(ro);
Console.WriteLine(flag);
RemotingObj ro2 = new RemotingObj();//本应用程序域中的对象
flag = System.Runtime.Remoting.RemotingServices.IsTransparentProxy(ro2);
Console.WriteLine(flag);
int a = ro.TypeHashCode();
a = ro2.TypeHashCode();//通过F10可以看到hashcode变化了 说明typeof(RemotingObj)在不同appdomain中表示不同的对象
Console.Read();
}
}
public class RemotingObj : MarshalByRefObject
{
public RemotingObj()
{
RemotingObj.Flag = 112;
Console.WriteLine(string.Format("RemotingObj({0}) is created in {1}", this.GetHashCode(), AppDomain.CurrentDomain.FriendlyName));
}
public int IndexOf(string str1, string str2)
{
return str1.IndexOf(str2);
}
public int TypeHashCode()
{
return typeof(RemotingObj).GetHashCode();
}
public static int Flag;
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace RemotingTest
{
class Program
{
static void Main(string[] args)
{
AppDomain ad = AppDomain.CreateDomain("AppDomain2");
RemotingObj ro = ad.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, "RemotingTest.RemotingObj") as RemotingObj;//ro是本地的一个透明代理,指向新创建应用程序域中的对象
Console.WriteLine(ro.IndexOf("Michael Jackson", "Jack"));//到这里远程对象一定已经创建了,但是RemotingObj.Flag仍然为0,说明本应用程序域中的Type对象没有被设置,设定的是ad中的typeof(RemotingObj)
bool flag = System.Runtime.Remoting.RemotingServices.IsTransparentProxy(ro);
Console.WriteLine(flag);
RemotingObj ro2 = new RemotingObj();//本应用程序域中的对象
flag = System.Runtime.Remoting.RemotingServices.IsTransparentProxy(ro2);
Console.WriteLine(flag);
int a = ro.TypeHashCode();
a = ro2.TypeHashCode();//通过F10可以看到hashcode变化了 说明typeof(RemotingObj)在不同appdomain中表示不同的对象
Console.Read();
}
}
public class RemotingObj : MarshalByRefObject
{
public RemotingObj()
{
RemotingObj.Flag = 112;
Console.WriteLine(string.Format("RemotingObj({0}) is created in {1}", this.GetHashCode(), AppDomain.CurrentDomain.FriendlyName));
}
public int IndexOf(string str1, string str2)
{
return str1.IndexOf(str2);
}
public int TypeHashCode()
{
return typeof(RemotingObj).GetHashCode();
}
public static int Flag;
}
}