【发布时间】:2018-03-24 22:15:12
【问题描述】:
我尝试在泛型类中使用 IComparable<T> 来比较 T 类型的元素,但出现以下错误:
“运算符'
我想知道是否可以解决这个问题。
这是一个简单的示例,当我将我的类定义为采用 int 时,IComparable<T> 正在工作:
public class IntStack : IComparable<IntStack>
{
public int[] stack = new int[2];
public int CompareTo(IntStack other)
{
// If the current stack < other stack return -1
// If the current stack > other stack return +1
// If current stack entries == other stack entries return 0
for (var current = 0; current < 2; current++)
{
if (stack[current] < other.stack[current])
{
return -1;
}
else if (stack[current] > other.stack[current])
{
return 1;
}
}
return 0;
}
}
IComparable<T> 现在在我将上面的类更改为泛型时在这里不起作用:
public class Mystack<T> : IComparable<Mystack<T>> where T : IComparable
{
public T[] stack = new T[2];
public int CompareTo(Mystack<T> other)
{
// If the current stack < other stack return -1
// If the current stack > other stack return +1
// If current stack entries == other stack entries return 0
for (var current = 0; current < 2; current++)
{
if (stack[current] < other.stack[current])
{
return -1;
}
else if (stack[current] > other.stack[current])
{
return 1;
}
}
return 0;
}
【问题讨论】:
标签: c# .net linq generics icomparable