问题
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.
回答1:
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
回答2:
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".
来源:https://stackoverflow.com/questions/3249991/how-net-overrides-non-virtual-method-in-net-remoting