c#类同时实现和继承

标签 c# class generics inheritance implementation

我想声明一个继承泛型类并实现接口(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 实现, 其中TSortableObject 的子类. 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/

相关文章:

c# - "for (bool flag = true; flag; flag = false) { ... }"- 这正常吗?

c# - Asp.net 缓存或手动缓存

c# - 输入 : How to bind an open generic with more than one type argument?

c++ - 采用预创建值的所有者对象?错误的设计?

c# - 泛型类型的泛型类型约束

c# - 如何在C#中从HtmlTable中提取数据并排列成行?

c# - 程序集中类的顺序

c++ - 有没有办法在 C++ 中延迟初始化成员变量(类)?

C# List<T> : How would this be done? 的泛型重载

c# - 当其中一个函数具有带约束的泛型参数时,无法声明两个同名函数