问题描述
我有一个 LinkedList 类,其中每个节点都有一个数据,它们的数据是泛型类型 T
public class LinkedList<T> where T : IComparable
{
}
在它的方法中,我比较了节点的数据,但是 我们知道,对象类型没有实现 IComparable,
LinkedList <int> listTest = new LinkedList<int>(); //it's OK
LinkedList <object> listTest2 = new LinkedList<object>(); //it doesn't work
但是我如何比较所有可以代替 T 的类型?
解决方法
您不能使用对象类型,因为它没有实现 IComparable 并且破坏了通用约束。
您需要创建一个实现 IComparable 接口的新对象。
public class Foo : IComparable {
}
var list = new LinkedList<Foo>();