我想声明一个继承泛型类并实现接口(interface)的类,例如:
public class SortableObject
{
int compare(SortableObejct obj);
}
public class List<T> where T is class
{
public void add(T obj);
public T peekCurrent();
}
public class SortedList<T> : List<T> where T : SortableObject, SortableObject
{
public override int compare(SortableObejct obj);
}
我要SortedList<T>
继承自 List<T>
并从 SortableObject
实现, 其中T
是 SortableObject
的子类. c# 编译器无法编译此类;在我看来,语法不支持这种情况。
有没有人遇到过这样的困难并有解决办法?
最佳答案
只需让 SortableObject
实现一个接口(interface):
public interface ISortableObject
{
int compare(SortableObejct obj);
}
public class SortableObject : ISortableObject
{
int compare(SortableObejct obj);
}
public class SortedList<T> : List<T> where T : SortableObject
这将确保如果它实际上是一个 SortableObject
,它已经实现了 ISortableObject
接口(interface)。
关于c#类同时实现和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19121804/