使用.Net Remoting/RealProxy 实现动态代理

public class ClassRealProxy<T>:RealProxy
    {
        private T tTarget;
        public ClassRealProxy(T target):base(typeof(T))
        {
            this.tTarget = target;
        }

        public override IMessage Invoke(IMessage msg)
        {
            BeforeProcess(msg);

            IMethodCallMessage callMessage = (IMethodCallMessage)msg;
            object returnValue = callMessage.MethodBase.Invoke(this.tTarget, callMessage.Args);

            return new ReturnMessage(returnValue, new object[0], 0, null, callMessage);
        }

        public void BeforeProcess(IMessage msg)
        {
            StackTrace trace = new StackTrace();
            string className = trace.GetFrame(3).GetMethod().DeclaringType.FullName;
            string methodName = trace.GetFrame(3).GetMethod().Name;
            Log4NetHelper.GetInstance().DebugLog(className+"."+methodName);
        }
    }


    public static class TransparentProxy
    {
        public static T Create<T>()
        {
            T instance = Activator.CreateInstance<T>();
            ClassRealProxy<T> realProxy = new ClassRealProxy<T>(instance);
            T transparentProxy = (T)realProxy.GetTransparentProxy();
            return transparentProxy;
        }

        public static T Create<T>(T type)
        {
            FormRealProxy<T> realProxy = new FormRealProxy<T>(type);
            T transparentProxy = (T)realProxy.GetTransparentProxy();
            return transparentProxy;
        }
    }

public class test :MarshalByRefObject,Itest

{

    public void TestMethod()

{

}

}

public interface Itest

{

    void TestMethod();

}

调用:

Itest itest = TransparentProxy.Create<test>();

itest.TestMethod();

猜你喜欢

转载自www.cnblogs.com/fanu/p/12749134.html