我创建了一个具有泛型实现的链接列表。但是Add(..)方法给出编译错误,说明:
错误4不能隐式地将'ds.MyNode< T >‘转换为'ds.MyNode< T >’
在代码实现之后:
public class MyNode<T>
{
public MyNode(T content)
{
Content = content;
}
public T Content { get; set; }
public MyNode<T> Next { get; set; }
}
public class MyLinkedList<T>
{
private int size;
private MyNode<T> head;
private MyNode<T> tail;
public MyNode<T> Tail
{
get { return tail; }
set { tail = value; }
}
public int Count
{
get { return size; }
set { size = value; }
}
public MyNode<T> Head
{
get { return head; }
set { head = value; }
}
public void Add<T>(MyNode<T> node)
{
size++;
if (head == null)
{
head = tail = node;
}
else
{
tail.Next = node;
tail = node;
}
}
}我不知道我在这里遗漏了什么,这个错误让人困惑,因为它说的两种类型都不是隐式可转换的。任何帮助都是非常感谢的。
我正在用.Net 4.0编译它
谢谢。
发布于 2015-06-26 08:22:00
只需从<T>方法中删除Add泛型类型,因为您的类已经是泛型的。
类和方法有可能具有相同的泛型类型(文档)名称:
如果定义了一个泛型方法,该方法将类型参数与包含类相同,编译器将生成警告CS0693,因为在方法范围内,为内部T提供的参数隐藏了为外部T提供的参数。如果需要灵活地使用类实例化时提供的类型参数以外的类型参数调用泛型类方法,则考虑为方法的类型参数提供另一个标识符,如下面示例中的
GenericList2<T>所示。 类GenericList { // CS0693 void SampleMethod() {}}类GenericList2 {//无警告空SampleMethod() {}
因此,您可能应该启用编译警告。来自ideone.com的编译器输出示例
prog.cs(39,22): warning CS0693: Type parameter `T' has the same name as the type parameter from outer type `Test.MyLinkedList<T>'
prog.cs(15,28): (Location of the symbol related to previous warning)
prog.cs(44,28): error CS0029: Cannot implicitly convert type `Test.MyNode<T> [prog, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]' to `Test.MyNode<T> [prog, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]'
prog.cs(48,26): error CS0029: Cannot implicitly convert type `Test.MyNode<T> [prog, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]' to `Test.MyNode<T> [prog, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]'
prog.cs(49,21): error CS0029: Cannot implicitly convert type `Test.MyNode<T> [prog, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]' to `Test.MyNode<T> [prog, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]'
Compilation failed: 3 error(s), 1 warnings发布于 2015-06-26 08:23:02
这是:
public void Add<T>(MyNode<T> node)这意味着T超过了对类级别T声明的跟踪,因此编译器将它们视为不同的类型。删除T将有效,因为很明显,您需要类T声明。
这样你就可以直观地看到它了,(不要用这个)也会工作
public void Add<TOther>(MyNode<T> node) where TOther : T因为您现在正在显式地告诉编译器,TOther是T类型的或派生的。
https://stackoverflow.com/questions/31068315
复制相似问题