[英]confused with <T>
观看了 sebastian lague 的 pathfiending.and 代码示例教程
public class Heap<T> where T : HeapIndex<T>
{
}
public interface HeapIndex<T> : IComparable<T>
{
int IndexHeap
{
get;
set;
}
}
public class Node : HeapIndex<Node>
{
public int IndexHeap { get; set; }
public int CompareTo([AllowNull] Node other)
{
return IndexHeap.CompareTo(other.IndexHeap);
}
}
和Heap<Node> heapNode = new Heap<Node>();
它的所有工作。 我开始阅读,我很困惑。 为什么我不能这样做
public class NodeInt : HeapIndex<int>
{
public int IndexHeap { get; set; }
public int CompareTo([AllowNull] int other)
{
return IndexHeap.CompareTo(other);
}
}
NodeInt nd = new NodeInt();
HeapIndex<NodeInt> hpD = nd as HeapIndex<NodeInt>;
Heap<NodeInt> heapInt = hpD as Heap<NodeInt>;
因为它不起作用Heap<NodeInt> heapNodeInt = new Heap<NodeInt>();
我可能只是不完全理解,并且非常模糊我的眼睛。 但我认为他的代码有效,任何满足 T 是接口实现要求的实例,然后你可以使用它来创建一个堆,为什么我不能只是Heap<NodeInt> heapNodeInt = new Heap<NodeInt>();
Heap<T> where T: HeapIndex<T>
意味着如果你想要Heap<NodeInt>
,那么NodeInt
应该继承HeapIndex<NodeInt>
只是因为T = NodeInt
在Heap
声明中。 但是您的NodeInt
是HeapIndex<int>
,因此它不符合要求,并且此代码将无法编译。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.