关于.net:C#如何确定某个类型是否实现了给定的接口?

C# How to determine if a type implements a given interface?

我想让以下内容返回true

1
var isIt = IsDisposable(typeof(TextWriter));

哪里:

1
2
3
4
5
6
bool IsIDisposable(Type t){
    ???
    // I tried:
    //return t.IsSubclassOf(typeof(IDisposable)); //returns false
    // the other t.IsXXX methods don't fit the requirement as far as I can tell
}


您可以使用IsAssignableFrom

1
bool IsDisposable = typeof(IDisposable).IsAssignableFrom(typeof(TextWriter));

演示


我发现它:type.getInterfaces()是我需要的:

1
2
3
bool IsIDisposable(Type t){
    return t.GetInterfaces().Contains(typeof(IDisposable));
}

从文件中,Type.GetInterfaces()返回:

Type: System.Type[]
An array of Type objects representing all the
interfaces implemented or inherited by the current Type.