• 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
  • 相关阅读:
    redis 持久化
    Hyper-V虚拟机Redhat添加网卡找不到网卡配置文件解决方法
    java 查看ssl log
    iptables配置https防火墙策略
    java 一致性哈希源码 转
    mysql主备配置方法
    hibernate 缓存配置
    Hibernate中文乱码
    HttpPost 中文编码问题 EntityBuilder
    apache 配置tomcat代理
  • 原文地址:https://www.cnblogs.com/tkt2016/p/8890575.html
Copyright © 2020-2023  润新知