.NET 如何重写 .NET Remoting 中的非虚拟方法?
考虑下面的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RemotingNonVirtualCall
{
class Program
{
static void Main(string[] args)
{
var domain = AppDomain.CreateDomain("Second Domain");
A extA = (A)domain.CreateInstanceAndUnwrap(typeof(A).Assembly.FullName, typeof(A).FullName);
Console.WriteLine(extA.CurrentDomain());
}
}
[Serializable]
sealed class A : MarshalByRefObject
{
public string CurrentDomain()
{
return AppDomain.CurrentDomain.FriendlyName;
}
}
}
方法 A::CurrentDomain 是非虚拟的,类 A 是密封的。但 CLR 会拦截方法调用并将其重定向到另一个实例。怎么可能呢?这是某种巫毒魔法吗? CLR 在调用从 MarshalByRefObject 类继承的对象的方法时是否会出现一些异常?它是如何执行的?
感谢您的提前。
Consider following piece of code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RemotingNonVirtualCall
{
class Program
{
static void Main(string[] args)
{
var domain = AppDomain.CreateDomain("Second Domain");
A extA = (A)domain.CreateInstanceAndUnwrap(typeof(A).Assembly.FullName, typeof(A).FullName);
Console.WriteLine(extA.CurrentDomain());
}
}
[Serializable]
sealed class A : MarshalByRefObject
{
public string CurrentDomain()
{
return AppDomain.CurrentDomain.FriendlyName;
}
}
}
Method A::CurrentDomain is non-virtual, class A is sealed. But CLR intercepts method call and redirect it to another instance. How it is possible? Is it some sort of voodoo magic? Does CLR make some exception in method calling for object inherited from MarshalByRefObject class? How is it performed?
Thanks for advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它本质上很神奇,即执行此操作的能力内置于 .NET 运行时中。好消息是,如果需要,您的代码也可以执行此操作: http://msdn.microsoft.com/en-us/library/system.runtime.remoting.proxies.realproxy.aspx
It's essentially magic, i.e. the ability to do this is built into the .NET runtime. The good news is that your code can also do this, if it needs to: http://msdn.microsoft.com/en-us/library/system.runtime.remoting.proxies.realproxy.aspx
JIT 编译器敏锐地意识到它为代理生成代码。您可以查看 SSCLI20 源代码, clr\src\vm\jithelpers.cpp,搜索“proxy”或更具体地说,"
IsTransparentProxyType
"。The JIT compiler is keenly aware that it generates code for a proxy. You can have a look-see with the SSCLI20 source code, clr\src\vm\jithelpers.cpp, search for "proxy" or more specifically, "
IsTransparentProxyType
".