使用.NET的Reflection.Emit生成一个接口
-
02-07-2019 - |
题
我需要在运行时生成一个新接口,其中所有成员都与现有接口相同,除了我将在某些方法上放置不同的属性(某些属性参数在运行时才知道)。如何实现?
解决方案
你的问题不是很具体。如果您使用更多信息更新它,我会用更多细节充实这个答案。
以下是所涉及的手动步骤的概述。
- 使用DefineDynamicAssembly创建装配
- 使用DefineDynamicModule创建模块
- 使用DefineType创建类型。请务必传递
TypeAttributes.Interface
以使您的类型成为接口。 - 迭代原始界面中的成员,并在新界面中构建类似的方法,根据需要应用属性。
- 调用
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类不隶属于 StackOverflow