How .NET overrides non-virtual method in .NET Remoting?

吃可爱长大的小学妹 提交于 2020-06-28 05:56:14

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!