C# How to determine if a type implements a given interface?
我想让以下内容返回
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 } |
号
您可以使用
1 | bool IsDisposable = typeof(IDisposable).IsAssignableFrom(typeof(TextWriter)); |
号
演示
我发现它:type.getInterfaces()是我需要的:
1 2 3 | bool IsIDisposable(Type t){ return t.GetInterfaces().Contains(typeof(IDisposable)); } |
从文件中,
Type: System.Type[]
An array of Type objects representing all the
interfaces implemented or inherited by the current Type.
号