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

后端 未结 1 1473
庸人自扰
庸人自扰 2021-01-20 21:15

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

public interface SortAlgorithm where T : System.IComparable

        
1条回答
  •  日久生厌
    2021-01-20 21:25

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

    Therefore, you should declare the class as:

    public class InsertionSort : SortAlgorithm where T : System.IComparable
    

    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, 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.

    0 讨论(0)
提交回复
热议问题