如何使用"is"来测试类型是否支持IComparable?

5 .net c# reflection icomparable

我想在排序之前检查一个类型是否支持IComparable,但是我发现检查一个类型是否支持使用"is"的IComparable接口并不总是给我正确的答案.例如,typeof(int) is IComparable返回false,即使int支持IComparable接口.

我注意到typeof(int).GetInterfaces()列出IComparable并typeof(int).GetInterface("IComparable")返回IComparable类型,那么为什么"is"不能像我预期的那样工作呢?

dri*_*iis 10

is适用于实例.当你说typeof(int) is IComparable,然后你真正检查的是类型是否System.Type实现IComparable,它不是.要使用is,您必须使用实例:

bool intIsComparable = 0 is IComparable; // true
Run Code Online (Sandbox Code Playgroud)


Jal*_*aid 5

int不支持IComparable,但为int类型不,这是它,你应该检查变量本身而不是它的类型,所以:

int foo = 5;
foo is IComparable;//the result is true, but of course it will not be true if you check typeof(foo)
Run Code Online (Sandbox Code Playgroud)