c# - 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 是一个类。
解决方案
正如 Ralf 在评论中所建议的,您可以尝试,
TypeBuilder tb = moduleBuilder.DefineType(
typeSignature,
TypeAttributes.Interface | TypeAttributes.Abstract | TypeAttributes.Public);
Type dynamicType = tb.CreateType();
dynamicType.IsInterface // true
推荐阅读
- java - 如何使用 Fake appupdatemanager 进行测试?
- java - 迭代地更改 Kafka Stream SessionWindows 的持续时间
- swift - Swift 5 中 UNUserNotificationCenter .requestAuthorization 的单元测试
- c# - 递增 LinkedList 的前“n”个整数
使用 Linq - php - 在 laravel 中使用队列的电子邮件之间的延迟
- r - R中的决策树图工具
- python - MongoDB 分组
- python - Pandas:过滤数据框中列中每个唯一单元格值的日期字段
- swiftui - SwiftUI 中 Stepper 的奇怪行为
- java - 使用 wsimport 从本地 WSDL 文件生成 Web 客户端