1

I want to declare a class that inherits a generic class and implements an interface, such as the following:

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);
}

I want SortedList<T> inherits from List<T> and implements from SortableObject, where T is a subclass from SortableObject. The c# compiler fails to compile such class; it seems to me that the grammar does not support this case.

Would anyone have met such difficulty and have a solution for it ?

4

2 回答 2

3

只需SortableObject实现一个接口:

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接口。

于 2013-10-01T16:55:46.687 回答
1

你需要让你的接口成为一个接口,而不是一个类,首先:

public interface ISortableObject
{
    int compare(ISortableObject obj);
}

接下来,您的声明语法List<T>不太正确;您没有正确声明通用约束。它应该是:

public class List<T> 
    where T : class
{
    public void add(T obj);
    public T peekCurrent();
}

最后,要让一个类从一个类继承、实现一个接口并添加通用约束,您需要按此顺序进行操作。定义通用约束后,您无法添加接口实现。

public class SortedList<T> : List<T>, ISortableObject
    where T : ISortableObject
{
    public override int compare(ISortableObject obj);
}
于 2013-10-01T16:58:18.333 回答