本文介绍了C#在接口及其实现程序类中均使用泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个适用于所有IComparable类型的接口.例如

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>

这是我这样做的目的.我希望所有排序算法都可以与实现IComparable接口的所有类型一起使用.并要提供一次接口中T是IComparable的子类的规范.但是当我这样做时,出现以下错误.

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.

错误1类型'T'不能用作通用类型或方法'Algorithms.SortingAlgorithm.SortAlgorithm'中的类型参数'T'.没有从"T"到"System.IComparable"的装箱转换或类型参数转换.

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

我不明白原因.我可以实现一个通用接口并使它的实现器类也通用,但是当在接口中指定规格(其中T: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)

推荐答案

所有派生的泛型类也将必须实现泛型约束.

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>

该错误的基本含义是不能保证通用参数 T (此时可以是任何类或结构)都不能实现 IComparable< T> ,受基类( SortAlgorithm 接口)的约束.

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

您还可以通过指定对 InsertionSort 类的约束来提供此保证,如上所述.

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

这篇关于C#在接口及其实现程序类中均使用泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 23:41