c# - 在哪里可以找到 IComparable 的 CompareTo 方法定义?
问题描述
在哪里可以找到 CompareTo 方法定义?
作为下面的代码,我可以通过实现 IComparable 接口来使用 CompareTo 方法。但是我没有在我的 Utilities 类中给出 CompareTo 方法的任何定义。我知道这是一个非常微不足道的问题。但我不明白一个类如何在不提供方法实现的情况下实现接口。
public class Utilities<T> where T : IComparable
{
public T Max(T a, T b)
{
return a.CompareTo(b) > 0 ? a : b;
}
}
解决方案
Your Utilities
class is not implementing IComparable
. You are saying that T
must implement IComparable
. If Utilities
were to implement IComparable
, it would look like this:
public class Utilities<T> : IComparable
You don't need to define a CompareTo
method in Utilities
because that should be defined in T
, whatever T
is.
For example, you can't use Foo
for T
because Foo
does not implement IComparable
:
class Foo {
// you must add a CompareTo method here in order to use Foo as T
// you must also add ": IComparable"
}
But you can use string
or int
or float
because they do implement IComparable
.
推荐阅读
- angular - 在日期选择器中设置最小日期
- node.js - 如何使用 sinon 模拟另一个文件中定义的常量并重新布线?
- python - 在 Python 中将对象列从 CSV 转换为 int
- flutter - Flutter - 错误:无法为颤振工具创建飞镖快照
- python - Unicode 符号“\u2019m”之前的 Python 字符串反斜杠
- javascript - Filter array of objects - erase last word in the string
- xpages - 未显示服务器端javascript的Lotus domino xpages全局对象
- continuous-integration - gitlab.com 项目概览页面上的存储含义和配额
- java - 我是否正确实施了广告,为什么没有显示?
- excel - “@”添加到使用 INDIRECT 公式的每一行