动态生成代码测试090325

        public static void Main(string[] args)
        {
            AppDomain apdom = Thread.GetDomain();
            AssemblyName an = new AssemblyName("testassambly");
            AssemblyBuilder ab = apdom.DefineDynamicAssembly(an, AssemblyBuilderAccess.RunAndSave);
            ModuleBuilder mb = ab.DefineDynamicModule("testmodule");
            TypeBuilder tb = mb.DefineType("testtype",TypeAttributes.Class);
            MethodBuilder meb = tb.DefineMethod("testmothod", MethodAttributes.Public);

            Type tConsole = typeof(System.Console);
            Type[] ts = new Type[]{typeof(string)};
            MethodInfo mif = tConsole.GetMethod("WriteLine",ts);

            ILGenerator ilg = meb.GetILGenerator();
            ilg.Emit(OpCodes.Nop);
            ilg.Emit(OpCodes.Ldstr,"this is a test mothod...");
            ilg.Emit(OpCodes.Call, mif);
            ilg.Emit(OpCodes.Nop);
            ilg.Emit(OpCodes.Ret);

            Type cc = tb.CreateType();           
            object oo = Activator.CreateInstance(cc);
            object oo1 = cc.InvokeMember("testmothod", BindingFlags.InvokeMethod, null, oo, null);

            Console.Read();
        }

 

 

http://www.cnblogs.com/sillyemperor/archive/2008/09/22/1295699.html#FeedBack

DynamicMethod

http://www.cnblogs.com/henryfan/archive/2008/05/21/1204180.html

posted @ 2009-03-25 16:28  阿网  阅读(167)  评论(0编辑  收藏  举报