Emit 网上转载的.留着以后用

通过Emit动态创建类(C#)
2009-08-16 22:02

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;

namespace EmitDemo
{
    public interface IHello
    {
        void SayHello(string toWhom);
    }

    class Program
    {
        static void Main(string[] args)
        {
            AssemblyName asmName = new AssemblyName();

            asmName.Name = "HelloWorld";

            AssemblyBuilder asmBuilder =
                Thread.GetDomain().DefineDynamicAssembly
            (asmName, AssemblyBuilderAccess.RunAndSave);

            ModuleBuilder modBuilder = asmBuilder.DefineDynamicModule
                            ("HelloWorld");

            TypeBuilder typeBuilder = modBuilder.DefineType(
                                    "Hello",
                                    TypeAttributes.Public,
                                    typeof(object),
                                    new Type[] { typeof(IHello) });

            MethodBuilder methodBuilder = typeBuilder.DefineMethod("SayHello",
                         MethodAttributes.Private | MethodAttributes.Virtual,
                         typeof(void),
                         new Type[] { typeof(string) });

            typeBuilder.DefineMethodOverride(methodBuilder,
                    typeof(IHello).GetMethod("SayHello"));

            ILGenerator il = methodBuilder.GetILGenerator();

            // string.Format("Hello, {0} World!", toWhom)
            //
            il.Emit(OpCodes.Ldstr, "Hello, {0} World!");
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Call, typeof(string).GetMethod
        ("Format", new Type[] { typeof(string), typeof(object) }));

            // Console.WriteLine("Hello, World!");
            //
            il.Emit(OpCodes.Call, typeof(Console).GetMethod
            ("WriteLine", new Type[] { typeof(string) }));
            il.Emit(OpCodes.Ret);

            Type type = typeBuilder.CreateType();

            IHello hello = (IHello)Activator.CreateInstance(type);

            hello.SayHello("Emit");

            Console.Read();
        }
    }
}

REF;http://www.codeproject.com/KB/msil/emithelper.aspx

Fortunately, there is an alternative way. Business Logic Toolkit for .NET provides a helper class, EmitHelper, which can make your life a little bit easy. It contains typed wrapper methods for almost all Emit commands and allows writing of source code that looks similar to MSIL.

The following examples show how to use the EmitHelper class with C#, VB.NET, and C++/CLI.

幸运的是,有人给我们封装了这个类,Business Logic Toolkit for .NET

下面是使用的例子

using System;

using BLToolkit.Reflection;
using BLToolkit.Reflection.Emit;

namespace EmitHelperDemo
{
    public interface IHello
    {
        void SayHello(string toWhom);
    }

    class Program
    {
        static void Main(string[] args)
        {
            EmitHelper emit = new AssemblyBuilderHelper("HelloWorld.dll")
                .DefineType ("Hello", typeof(object), typeof(IHello))
                .DefineMethod(typeof(IHello).GetMethod("SayHello"))
                .Emitter;

            emit
                // string.Format("Hello, {0} World!", toWhom)
                //
                .ldstr   ("Hello, {0} World!")
                .ldarg_1
                .call    (typeof(string), "Format", typeof(string),
                                            typeof(object))

                // Console.WriteLine("Hello, World!");
                //
                .call    (typeof(Console), "WriteLine", typeof(string))
                .ret()
                ;

            Type   type = emit.Method.Type.Create();

            IHello hello = (IHello)TypeAccessor.CreateInstance(type);

            hello.SayHello("C#");
        }
    }
}

posted @ 2013-03-30 11:35  丫的  阅读(224)  评论(0编辑  收藏  举报