【发布时间】:2021-09-03 14:30:58
【问题描述】:
我的任务是使用单链表和泛型创建一个集合。为了创建一个单链表,我做了一个特殊的类,没什么不寻常的。
public class Node<T>
{
public Node(string name)
{
Name = 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 head;
T tail;
T current;
int count = 0;
public void Add (T item)
{
Node<T> node = new(null);
if (head == null)
{
head = (T)node;
}
else
{
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 };
}
但它不起作用。你对此有什么想法吗?
【问题讨论】:
-
我不明白你为什么首先需要
MyCustomCollection?你的Node<T>类已经是你所需要的单链表了。 -
您的自定义集合要求它由派生自
Node<T>本身的类型参数化。对于集合类来说,这似乎是一个不寻常的要求。为什么要添加where? -
您的
Node<T>类中没有任何通用内容。您有一个字符串,并且您有对下一个节点的引用。您没有任何通用数据成员。你可以简单地拥有一个没有任何泛型的Node类
标签: c# visual-studio generics singly-linked-list