MSIL实用指南-类相关生成

一、创建class
用MethodBuilder的DefineType方法,可以指定父类,得到一个TypeBuilder对象。


二、实现继承接口
用TypeBuilder的AddInterfaceImplementation方法。

三、显示方法重写
用TypeBuilder的DefineMethodOverride方法。


完整代码如下:

 

using System;
using System.Reflection;
using System.Reflection.Emit;

namespace LX1_ILDemo
{
    class Demo31_Class
    {
        static string binaryName = "Demo31_Class.dll";
        static string namespaceName = "LX1_ILDemo";
        static string typeName = "DemoClass";

        static AssemblyBuilder assemblyBuilder;
        static ModuleBuilder moduleBuilder;
        static TypeBuilder typeBuilder;
        static MethodBuilder compareToMethod;

        public static void Generate()
        {
            InitAssembly();
            typeBuilder = moduleBuilder.DefineType(
                namespaceName + "." + typeName,
                TypeAttributes.Public ,
                typeof(object)
                );
            typeBuilder.AddInterfaceImplementation(typeof( System.IComparable));

            GenerateCompareTo();
            typeBuilder.DefineMethodOverride(compareToMethod, typeof(System.IComparable).GetMethod("CompareTo", new Type[] { typeof(object) }));
            SaveAssembly();
            Console.WriteLine("生成成功");
        }

        static void GenerateCompareTo()
        {
            compareToMethod = typeBuilder.DefineMethod("CompareTo",
                MethodAttributes.Public | MethodAttributes.Virtual,
                 typeof(int),
            new Type[] { typeof(object) });
            ILGenerator ilGenerator = compareToMethod.GetILGenerator();
            ilGenerator.Emit( OpCodes.Ldc_I4_0 );
            ilGenerator.Emit(OpCodes.Ret);
        }

        static void InitAssembly()
        {
            AssemblyName assemblyName = new AssemblyName(namespaceName);
            assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
            moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, binaryName);
        }

        static void SaveAssembly()
        {
            Type t = typeBuilder.CreateType(); //完成Type,这是必须的
            assemblyBuilder.Save(binaryName);
        }
    }
}
View Code

 

posted @ 2018-04-20 13:52  Z语言  阅读(131)  评论(0编辑  收藏  举报