[英]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
. 我希望
SortedList<T>
继承自List<T>
并从SortableObject
实现,其中T
是SortableObject
的子类。 The c# compiler fails to compile such class; c#编译器无法编译这样的类; 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: 只需让
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
This will ensure that if it is in fact a SortableObject
it has implemented the ISortableObject
interface. 这将确保如果它实际上是一个
SortableObject
它已经实现了ISortableObject
接口。
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; 接下来,声明
List<T>
语法不太正确; 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.