我有一個任務是使用單鏈表和泛型來創建一個集合。為了創建一個單鏈表,我做了一個特殊的類,沒什么特別的。
public class Node<T>
{
public Node(string name)
{
名稱 = 名稱。
}
public string Name { get; set; }
public Node< T> Next { get; set; }
然后我做了一個簡短的界面,我寫了所有必要的東西來處理串列。這里有一些片段可以展示:
interface ICustomCollection<T>。
{
void Add(T item) 。
然后我在一個新的集合類中使用了這個介面:
class MyCustomCollection<T> : ICustomCollection<T> where T: Node<T>
{
T頭。
T tail;
T當前。
int count = 0;
public void Add (T item)
{
Node<T> node = new(null)。
if (head == null)
{
head = (T)node;
}
else (head ==null) { head = (T)node; }
{
tail.Next = node;
}
tail = (T)node;
count ;
current = tail;
}
}
讓它成為集合的所有功能。所以我創建了一個名為Person的新類,其名稱為:
。public class Person
{
string name。
}
所以我需要創建一個類的實體來使用這個集合:
MyCustomCollection<Person> people;
但是現在我有一個編譯器錯誤CS0311,說沒有從 "Person "到 "Node "的隱式參考轉換。我真的不明白該怎么做,我甚至試圖做一些事情:
public static explicit operator Node< Person>(Person person)。
{
return new Node<Person>(person.name){ Next = null, Name = person.name };
}
但它沒有作業。你對此有什么想法嗎?
uj5u.com熱心網友回復:
你不想要求集合只能包含那些本身來自Node<T>的東西。所以不要把它作為一個要求。只要在內部使用Node<T>:
class MyCustomCollection<T> 。ICustomCollection<T>
{
Node<T> head。
Node<T> tail。
Node<T> current。
int count = 0;
在這一點上,你也可以考慮將Node類移到你的集合類中,并使其成為私有的(如果你這樣做,你將不再需要對Node本身進行引數化,因為它可以使用集合的包圍T引數)
你可能還需要使你的Node<T>能夠存盤一個T作為一個屬性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/318621.html
標籤:
