watched tutorial from sebastian lague for pathfiending.and code example
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);
}
}
and Heap<Node> heapNode = new Heap<Node>();
all its work. i start read for and i confused. why i cant do with this way
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>;
bacause its not work Heap<NodeInt> heapNodeInt = new Heap<NodeInt>();
I probably just do not fully understand, and terribly blurred my eyes. but I thought that his code works, any instance that meets the requirement where T is an interface implementation, then you can use it to create a heap why i cant just Heap<NodeInt> heapNodeInt = new Heap<NodeInt>();
Heap<T> where T: HeapIndex<T>
means that if you want Heap<NodeInt>
, then the NodeInt
should inherit HeapIndex<NodeInt>
just because T = NodeInt
in the Heap
declaration. But your NodeInt
is HeapIndex<int>
, so it does not meet requirement and this code won't compile.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.