简体   繁体   中英

c# class implements and inherits at the same time

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 ?

Just make SortableObject implement an 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

This will ensure that if it is in fact a SortableObject it has implemented the ISortableObject interface.

You need to make your interface an interface, rather than a class, to start with:

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

Next, your syntax for declaring List<T> wasn't quite right; you weren't declaring the generic constraint properly. It should be:

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

Finally, to have a class inherit from a class, implement an interface, and also add generic constraints, you need to do them in that order. You can't add the interface implementation after the generic constraints are defined.

public class SortedList<T> : List<T>, ISortableObject
    where T : ISortableObject
{
    public override int compare(ISortableObject obj);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM