以下代码将无法编译:
class Test<T> where T : class, IComparable
{
public bool IsGreater(T t1, T t2)
{
return t1 > t2; // Cannot apply operator '>' to operands of type 'T' and 'T'
}
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能让它发挥作用?我希望它适用于 T = int、double、DateTime等。
IComparable您在此处用作类型约束的接口为您提供了一个方法CompareTo。所以你可以这样做:
public bool IsGreater(T t1, T t2)
{
return t1.CompareTo(t2) > 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
141 次 |
| 最近记录: |