【问题标题】:C# Reflection Create Interface at RuntimeC# 反射在运行时创建接口
【发布时间】:2019-10-22 09:57:14
【问题描述】:

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

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 是一个类。

【问题讨论】:

  • dynamicType.GetType() 为您提供 Type 类。而 Type 是一个类。您大概想检查 dynamicType.IsInterface。
  • 你大概希望你的界面是公开的。私有接口没什么用。

标签: c# reflection .net-core runtime


【解决方案1】:

按照拉尔夫在评论中的建议,你可以试试,

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

dynamicType.IsInterface      // true

【讨论】:

    猜你喜欢
    • 2011-05-05
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多