我有以下内容:
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])
{
...
}
}
我如何检查该类型是从 MyInterface 继承的? keywork 会以这种方式工作吗?
谢谢。
最佳答案
不,是
仅适用于检查对象的类型,不适用于给定的类型
。你要Type.IsAssignableFrom
:
if (attr != null && typeof(IInterface).IsAssignableFrom(type))
注意这里的顺序。我发现我几乎总是使用typeof(...)
作为调用的目标。基本上它要返回 true,目标必须是“父”类型,参数必须是“子”类型。
关于c# - 如何检查该类型是从某些接口(interface)继承的 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4334710/