我有兩種類型的節點,一種是MyLinkNode它用作基礎,另一種是繼承MyLinkNode的GraphNode。C#泛型,其中T類:(繼承類)
我嘗試使用MyLinkNode創建MyQueue。一切都還好,直到我嘗試將GraphNode添加到MyQueue。由於GraphNode更大,我無法使用MyQueue。
另一種方法是爲GraphNode創建另一個隊列,但這意味着如果我有更多類型的節點,我需要創建大量的類。 有什麼建議嗎?
public class MyQueue<T> where T : MyLinkNode<T>
{
private T Head;
private T Last;
public MyQueue(){ ... }
public void Enqueue(T item)
{
item.Prev = Last;
Last.Next = item;
Last = item;
}
}
public class MyGraphQueue
{
//everything is the same with MyQueue besides the Node Type
//I don't want to create like this.
private GraphNode Head;
private GraphNode Last;
public MyGraphQueue(){ ... }
public void Enqueue(GraphNode item)
{
item.Prev = Last;
Last.Next = item;
Last = item;
}
}
public class MyLinkNode<T>
{
public T data { get; set; }
public MyLinkNode<T> Next { get; set; }
public MyLinkNode<T> Prev { get; set; }
}
public class GraphNode<T> : MyLinkNode<T>
{
public GraphNode()
{
this.adjacencyNodes = new List<GraphNode<T>>();
this.isVisited = false;
}
public List<GraphNode<T>> adjacencyNodes;
public bool isVisited { get; set; }
}
public void BFS<T>(GraphNode<T> v)
{
MyQueue<GraphNode<T>> queue = new MyQueue<GraphNode<T>>(); // error, can't implicit convert GraphNode to MyLinkNode<T>
MyGraphQueue queue = new MyGraphQueue(); //It's how I do now.
}
我不明白你的意思「不能使用GraphNode的MyQueue,因爲它更大。」 –
對於我的糟糕解釋感到抱歉。如果我用GraphNode使用MyQueue,編譯器會說它是非法的,因爲GraphNode不能隱式轉換爲MyLinkNode。 –