7

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

4

2 回答 2

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);

这将创建以下内容:

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

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

于 2009-04-30T18:45:56.373 回答
8

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

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

  1. 使用 DefineDynamicAssembly 创建装配
  2. 使用 DefineDynamicModule 创建模块
  3. 使用 DefineType 创建类型。确保通过TypeAttributes.Interface以使您的类型成为接口。
  4. 迭代原始接口中的成员并在新接口中构建类似的方法,并根据需要应用属性。
  5. 调用TypeBuilder.CreateType以完成构建您的界面。
于 2008-09-25T22:29:20.957 回答