使用.NET';s Reflection.Emit生成一个接口

使用.NET';s Reflection.Emit生成一个接口,.net,reflection.emit,.net,Reflection.emit,我需要在运行时使用与现有接口相同的所有成员生成一个新接口,除了我将在一些方法上放置不同的属性(一些属性参数在运行时之前是未知的)。如何实现这一目标?你的问题不是很具体。如果你用更多的信息来更新它,我会用更多的细节来充实这个答案 下面是有关手动步骤的概述 使用DefinedDynamicAssembly创建部件 使用DefinedDynamicModule创建一个模块 使用DefineType创建类型。确保传递TypeAttributes.Interface以使您的键入成为接口 迭代原始接口中的成

我需要在运行时使用与现有接口相同的所有成员生成一个新接口,除了我将在一些方法上放置不同的属性(一些属性参数在运行时之前是未知的)。如何实现这一目标?

你的问题不是很具体。如果你用更多的信息来更新它,我会用更多的细节来充实这个答案

下面是有关手动步骤的概述

  • 使用DefinedDynamicAssembly创建部件
  • 使用DefinedDynamicModule创建一个模块
  • 使用DefineType创建类型。确保传递
    TypeAttributes.Interface
    以使您的键入成为接口
  • 迭代原始接口中的成员,并在新接口中构建类似的方法,根据需要应用属性
  • 调用
    TypeBuilder.CreateType
    完成界面的构建

  • 要使用具有属性的接口动态创建程序集,请执行以下操作:

    using System.Reflection;
    using System.Reflection.Emit;
    
    // Need the output the assembly to a specific directory
    string outputdir = "F:\\tmp\\";
    string fname = "Hello.World.dll";
    
    // Define the assembly name
    AssemblyName bAssemblyName = new AssemblyName();
    bAssemblyName.Name = "Hello.World";
    bAssemblyName.Version = new system.Version(1,2,3,4);
    
    // Define the new assembly and module
    AssemblyBuilder bAssembly = System.AppDomain.CurrentDomain.DefineDynamicAssembly(bAssemblyName, AssemblyBuilderAccess.Save, outputdir);
    ModuleBuilder bModule = bAssembly.DefineDynamicModule(fname, true);
    
    TypeBuilder tInterface = bModule.DefineType("IFoo", TypeAttributes.Interface | TypeAttributes.Public);
    
    ConstructorInfo con = typeof(FunAttribute).GetConstructor(new Type[] { typeof(string) });
    CustomAttributeBuilder cab = new CustomAttributeBuilder(con, new object[] { "Hello" });
    tInterface.SetCustomAttribute(cab);
    
    Type tInt = tInterface.CreateType();
    
    bAssembly.Save(fname);
    
    这将产生以下结果:

    namespace Hello.World
    {
       [Fun("Hello")]
       public interface IFoo
       {}
    }
    

    添加方法通过调用TypeBuilder.DefineMethod使用MethodBuilder类。

    Nah,这很酷。我以前不需要使用反射。发射,所以我只想看看是否有人能在我邪恶的总体计划中发现一个绊脚石。