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

7

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

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类添加方法。


8
你的问题不够具体。如果您提供更多信息,我会补充这个答案的细节。
以下是涉及的手动步骤概述:
1. 使用DefineDynamicAssembly创建一个程序集。 2. 使用DefineDynamicModule创建一个模块。 3. 使用DefineType创建类型。请确保传递TypeAttributes.Interface以使您的类型成为接口。 4. 遍历原始接口中的成员,并在新接口中构建类似的方法,必要时应用属性。 5. 调用TypeBuilder.CreateType来完成接口的构建。

没事,很好。我以前没有使用Reflection.Emit,所以只是想看看是否有人能够发现我的邪恶大师计划中的绊脚石。 - Matt Howells

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接