C # emit implements a proxy for a class

Source: Internet
Author: User
Tags emit

usingSystem;usingSystem.Linq;usingSystem.Reflection;usingSystem.Reflection.Emit;namespaceemitcreatedynamicproxy{classProgram {Static voidMain (string[] args) {            varCommand = proxy.of<command>(); Command.            Execute ();        Console.ReadLine (); }    }     Public classCommand { Public Virtual voidExecute () {Console.WriteLine ("Hello kitty!"); }    }      Public classInterceptor { Public ObjectInvoke (Object@object,string@method,Object[] Parameters) {Console.WriteLine (string. Format ("before invoke [{0}] ...", @method)); varRetobj =@object. GetType (). GetMethod (@method).            Invoke (@object, parameters); Console.WriteLine (string. Format ("After invoke [{0}] ...", @method)); returnRetobj; }    }     Public classProxy { Public StaticT of<t>()         {            stringnameofassembly =typeof(T). Name +"proxyassembly"; stringNameofmodule =typeof(T). Name +"Proxymodule"; stringNameoftype =typeof(T). Name +"Proxy"; varAssemblyName =NewAssemblyName (nameofassembly); varAssembly =Appdomain.currentdomain.            DefineDynamicAssembly (AssemblyName, Assemblybuilderaccess.run); varModuleBuilder =Assembly.                      DefineDynamicModule (Nameofmodule); varTypeBuilder =Modulebuilder.definetype (Nameoftype, Typeattributes.public,typeof(T)); Injectinterceptor<T>(TypeBuilder); vart =TypeBuilder.CreateType (); return(t) activator.createinstance (t); }        Private Static voidInjectinterceptor<t>(TypeBuilder TypeBuilder) {//----define fields----            varFieldinterceptor =Typebuilder.definefield ("_interceptor",typeof(Interceptor), fieldattributes.private); //----define costructors----            varConstructorBuilder =Typebuilder.defineconstructor (Methodattributes.public, Callingconventions.standard,NULL); varIlofctor =Constructorbuilder.getilgenerator ();            Ilofctor.emit (OPCODES.LDARG_0); Ilofctor.emit (Opcodes.newobj,typeof(Interceptor). GetConstructor (Newtype[0]));            Ilofctor.emit (OPCODES.STFLD, fieldinterceptor);            Ilofctor.emit (Opcodes.ret); //----Define methods----            varMethodsoftype =typeof(T). GetMethods (BindingFlags.Public |bindingflags.instance);  for(vari =0; i < methodsoftype.length; i++)            {                varMETHOD =Methodsoftype[i]; varMethodparametertypes =method. GetParameters (). Select (P=p.parametertype).                ToArray (); varMethodBuilder =Typebuilder.definemethod (method. Name, Methodattributes.public|methodattributes.virtual, Callingconventions.standard, method.                ReturnType, methodparametertypes); varIlofmethod =Methodbuilder.getilgenerator ();                Ilofmethod.emit (OPCODES.LDARG_0);                Ilofmethod.emit (OPCODES.LDFLD, fieldinterceptor); //Create instance of TIlofmethod.emit (Opcodes.newobj,typeof(T). GetConstructor (Newtype[0])); Ilofmethod.emit (Opcodes.ldstr, method.                Name); //build the method parameters                if(Methodparametertypes = =NULL) {ilofmethod.emit (opcodes.ldnull); }                Else                {                    varParameters = Ilofmethod.declarelocal (typeof(Object[]));                    Ilofmethod.emit (OPCODES.LDC_I4, methodparametertypes.length); Ilofmethod.emit (Opcodes.newarr,typeof(Object));                    Ilofmethod.emit (opcodes.stloc, parameters);  for(varj =0; J < Methodparametertypes.length; J + +) {ilofmethod.emit (opcodes.ldloc, parameters);                        Ilofmethod.emit (OPCODES.LDC_I4, J); Ilofmethod.emit (Opcodes.ldarg, J+1);                    Ilofmethod.emit (OPCODES.STELEM_REF);                } ilofmethod.emit (Opcodes.ldloc, parameters); }                //Call Invoke () Method of InterceptorIlofmethod.emit (Opcodes.callvirt,typeof(Interceptor). GetMethod ("Invoke")); //Pop the stack if return void                if(method. ReturnType = =typeof(void) {ilofmethod.emit (opcodes.pop); }                // CompleteIlofmethod.emit (Opcodes.ret); }        }    }}

C # emit implements a proxy for a class

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.