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

有帮助吗?

解决方案

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

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

  1. 使用DefineDynamicAssembly创建装配
  2. 使用DefineDynamicModule创建模块
  3. 使用DefineType创建类型。请务必传递 TypeAttributes.Interface 以使您的类型成为接口。
  4. 迭代原始界面中的成员,并在新界面中构建类似的方法,根据需要应用属性。
  5. 调用 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类
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top