C# using Generics both in the Interface and its implementor class

半世苍凉 提交于 2020-02-15 08:44:08

问题


I want to create an interface that works for all the IComparable types. For example

public interface SortAlgorithm<T> where T : System.IComparable<T>
{
    List<T> Sort(List<T> input);
}

And I want its implementors to be generic as well with the same specification I provide in the interface. Like the example below

public class InsertionSort<T> : SortAlgorithm<T>

Here is my purpose for doing this. I want all my sorting algorithms to work with all types that implements the IComparable interface. And want to provide the specification that the T is a subclass of IComparable once in the interface. But when I do this, I get the following error.

Error 1 The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Algorithms.SortingAlgorithm.SortAlgorithm'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IComparable'.

I did not understand the reason for this. I can implement a generic interface and make its implementor classes generic as well but I can't do the same when give a specification in the interface (where T : System.IComparable)


回答1:


All derived generic classes will also have to implement the generic constraint.

Therefore, you should declare the class as:

public class InsertionSort<T> : SortAlgorithm<T> where T : System.IComparable<T>

What the error basically says is that the generic parameter T (which at this point can be any class or struct) is not guaranteed to implement IComparable<T>, as constrained by the base class (the SortAlgorithm interface).

You can provide this guarantee by specifying the constraint on the InsertionSort class as well, as presented above.



来源:https://stackoverflow.com/questions/13219770/c-sharp-using-generics-both-in-the-interface-and-its-implementor-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!