具有通用实现的单链接列表

akk*_*a16 2 c# generics linked-list

我创建了一个带有通用实现的链表.但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;
        }
    }       
}
Run Code Online (Sandbox Code Playgroud)

我不确定我在这里缺少什么,错误令人困惑,因为它所说的两种类型都不是隐式可兑换的.任何帮助表示赞赏.

我正在针对.Net 4.0进行编译

谢谢.

awe*_*oon 7

只需<T>Add方法中删除泛型类型,因为您的类已经是通用的.

类和方法可以具有相同的泛型类型(docs)名称:

如果定义一个采用与包含类相同类型参数泛型方法,则编译器会生成警告CS0693,因为在方法范围内,为内部T提供的参数隐藏了为外部T提供的参数.如果您需要使用类型参数调用泛型类方法的灵活性,而不是在实例化类时提供的类型参数,请 考虑为方法的类型参数提供另一个标识符,如以下示例所示.GenericList2<T>

class GenericList<T>
{
    // CS0693 
    void SampleMethod<T>() { }
}

class GenericList2<T>
{
    //No warning 
    void SampleMethod<U>() { }
}
Run Code Online (Sandbox Code Playgroud)

所以,您应该启用编译警告.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
Run Code Online (Sandbox Code Playgroud)