如何检查该类型是从某个接口c#继承的

ibu*_*kov 26 c# reflection inheritance interface

我有以下内容:

Assembly asm = Assembly.GetAssembly(this.GetType());

foreach (Type type in asm.GetTypes())
{
    MyAttribute attr = Attribute.GetCustomAttribute(type, typeof(MyAttribute))    as MyAttribute;
     if(attr != null && [type is inherited from Iinterface])
     {
        ...
     }

}
Run Code Online (Sandbox Code Playgroud)

如何检查该类型是否继承自MyInterface?键盘工作是否会以这种方式工作?

谢谢.

Jon*_*eet 47

不,is仅适用于检查对象的类型,而不适用于给定的对象Type.你想要Type.IsAssignableFrom:

if (attr != null && typeof(IInterface).IsAssignableFrom(type))
Run Code Online (Sandbox Code Playgroud)

请注意这里的订单.我发现,我几乎总是使用typeof(...)目标的呼叫.基本上,它返回true,目标必须是"父"类型,参数必须是"子"类型.