代码之家  ›  专栏  ›  技术社区  ›  Matt Howells

使用.NET的Reflection.Emit生成接口

  •  7
  • Matt Howells  · 技术社区  · 17 年前

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

    2 回复  |  直到 15 年前
        1
  •  12
  •   Colin Burnett    17 年前

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

    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类。

        2
  •  8
  •   Curt Hagenlocher    17 年前

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

    1. 使用DefinedDynamicModule创建一个模块
    2. TypeAttributes.Interface 使您的类型成为接口。
    3. 迭代原始接口中的成员,并在新接口中构建类似的方法,根据需要应用属性。
    4. TypeBuilder.CreateType 完成界面的构建。