C# 反射在运行时创建接口
C# Reflection Create Interface at Runtime
有没有办法在运行时创建接口?我试过了:
string typeSignature = "IFoo";
...
TypeBuilder tb = moduleBuilder.DefineType(typeSignature, TypeAttributes.Interface);
但这给出了一个例外:
'Interface must be declared abstract.'
所以我尝试了:
TypeBuilder tb = moduleBuilder.DefineType(typeSignature, TypeAttributes.Interface
| TypeAttributes.Abstract);
Type dynamicType = tb.CreateType();
但是 dynamicType.GetType().IsInterface
returns 错误。出于某种原因,它认为 dynamicType 是 class.
根据Ralf在评论中的建议,你可以试试,
TypeBuilder tb = moduleBuilder.DefineType(
typeSignature,
TypeAttributes.Interface | TypeAttributes.Abstract | TypeAttributes.Public);
Type dynamicType = tb.CreateType();
dynamicType.IsInterface // true
有没有办法在运行时创建接口?我试过了:
string typeSignature = "IFoo";
...
TypeBuilder tb = moduleBuilder.DefineType(typeSignature, TypeAttributes.Interface);
但这给出了一个例外:
'Interface must be declared abstract.'
所以我尝试了:
TypeBuilder tb = moduleBuilder.DefineType(typeSignature, TypeAttributes.Interface
| TypeAttributes.Abstract);
Type dynamicType = tb.CreateType();
但是 dynamicType.GetType().IsInterface
returns 错误。出于某种原因,它认为 dynamicType 是 class.
根据Ralf在评论中的建议,你可以试试,
TypeBuilder tb = moduleBuilder.DefineType(
typeSignature,
TypeAttributes.Interface | TypeAttributes.Abstract | TypeAttributes.Public);
Type dynamicType = tb.CreateType();
dynamicType.IsInterface // true