首页 > 解决方案 > C# 反射在运行时创建接口

问题描述

有没有办法在运行时创建接口?我试过:

string typeSignature = "IFoo";
...
TypeBuilder tb = moduleBuilder.DefineType(typeSignature, TypeAttributes.Interface);

但这给出了一个例外:

“接口必须声明为抽象的。”

所以我尝试了:

TypeBuilder tb = moduleBuilder.DefineType(typeSignature, TypeAttributes.Interface 
    | TypeAttributes.Abstract);
Type dynamicType = tb.CreateType();

dynamicType.GetType().IsInterface返回假。出于某种原因,它认为 dynamicType 是一个类。

标签: c#reflection.net-coreruntime

解决方案


正如 Ralf 在评论中所建议的,您可以尝试,

TypeBuilder tb = moduleBuilder.DefineType(
    typeSignature,
    TypeAttributes.Interface | TypeAttributes.Abstract | TypeAttributes.Public);
Type dynamicType = tb.CreateType();

dynamicType.IsInterface      // true

推荐阅读