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

Mat*_*lls 7 .net reflection.emit

我需要在运行时生成一个新接口,其中所有成员都与现有接口相同,除了我将在某些方法上放置不同的属性(某些属性参数在运行时才知道).如何实现?

Col*_*ett 12

要使用具有以下属性的接口动态创建程序集:

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);
Run Code Online (Sandbox Code Playgroud)

这创造了以下内容:

namespace Hello.World
{
   [Fun("Hello")]
   public interface IFoo
   {}
}
Run Code Online (Sandbox Code Playgroud)

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


Cur*_*her 8

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

以下是所涉及的手动步骤的概述.

  1. 使用DefineDynamicAssembly创建装配
  2. 使用DefineDynamicModule创建一个模块
  3. 使用DefineType创建类型.一定要通过TypeAttributes.Interface使您的类型成为一个界面.
  4. 迭代原始界面中的成员并在新界面中构建类似的方法,根据需要应用属性.
  5. 打电话TypeBuilder.CreateType完成界面建设.