我该如何使用“是”测试类型是否支持 IComparable?
我想在排序之前检查类型是否支持 IComparable,但我发现使用“is”检查类型是否支持 IComparable 接口并不总是能给我正确的答案。例如,typeof(int) is IComparable
返回 false,即使 int 确实支持 IComparable 接口。
我注意到 typeof(int).GetInterfaces()
列出了 IComparable 并且 typeof(int).GetInterface("IComparable")
返回 IComparable 类型,那么为什么“is”会返回 IComparable 类型呢?没有按我的预期工作?
I want to check if a type supports IComparable before sorting it, but I've found that checking if a type supports the IComparable interface using "is" does not always give me the correct answer. For example, typeof(int) is IComparable
returns false, even though int does support the IComparable interface.
I note that typeof(int).GetInterfaces()
lists IComparable and typeof(int).GetInterface("IComparable")
returns the IComparable type, so why does "is" not work as I expect?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
is
适用于实例。当您说typeof(int) 是 IComparable
时,那么您真正检查的是类型System.Type
是否实现了IComparable
,而它并没有实现。要使用is
,您必须使用实例:is
works on an instance. When you saytypeof(int) is IComparable
, then what you are really checking whether the typeSystem.Type
implementsIComparable
, which it does not. To useis
, you must use an instance:int
确实支持IComparable
但 int 的类型不支持,就是这样,您应该检查变量本身而不是它的 类型,因此:The
int
does supportIComparable
but the type of int doesn't, that is it, you should check the variable itself not its Type, so:is
运算符期望左侧有一个实例:编译(带有关于始终为 true 的警告)。
并且“
typeof(int) is IComparable
returns false”那是因为您询问 Type 类(的实例)是否是 IComparable。它不是。
The
is
operator expects an instance on the left side:Compiles (with a Warning about always being true).
And "
typeof(int) is IComparable
returns false"That is because you are asking whether (an instance of) the Type class is IComparable. It is not.