如何在c#或CS1503中使用通用变量

如何在c#或CS1503中使用通用变量,c#,.net,compiler-errors,C#,.net,Compiler Errors,我用链表写一个哈希表 这是节点元素的代码 class ListNode<T> { public T value{get; set;} public ListNode<T> next{get; set;} public void Insert(T newValue){ value = newValue; } } 类列表节点 { 公共T值{get;set;} 公

我用链表写一个哈希表

这是节点元素的代码

    class ListNode<T>
    {
        public T value{get; set;}
        public ListNode<T> next{get; set;}

        public void Insert(T newValue){
            value = newValue;
        }
    }
类列表节点
{
公共T值{get;set;}
公共ListNode下一个{get;set;}
公共无效插入(T newValue){
值=新值;
}
}
这是Linkedlist的实现

    class LinkedL<T> : IEnumerable<T>
    {
        ListNode<T> head;
        ListNode<T> tail;

        public void Add(T newVal){
            ListNode<T> node = new ListNode<T>();
            node.Insert(newVal);

            if (head == null)
                head = node;
            else
                tail.next = node;
            
            tail = node;
        }
     }
类LinkedL:IEnumerable
{
节点头;
链节尾;
公共无效添加(T newVal){
ListNode节点=新建ListNode();
节点插入(newVal);
if(head==null)
头部=节点;
其他的
tail.next=节点;
尾=节点;
}
}
最后是我的哈希表和一个简单的hash func X%N

    class HashTable 
    {
        int N;
        public LinkedL<ListNode<int>>[] values; 

        public HashTable(int n){
            N = n;
            values = new LinkedL<ListNode<int>>[N];
         }

        public void Insert(int newValue){
            var mod = newValue % N;
            values[mod].Add(newValue);
        }       
    }
类哈希表
{
int N;
公共LinkedL[]值;
公共哈希表(int n){
N=N;
值=新的LinkedL[N];
}
公共无效插入(int newValue){
var mod=新值%N;
值[mod]。添加(newValue);
}       
}
当我尝试向哈希表实例编译器插入(int)时,会抛出一个CS1503错误

无法从“int”转换为“this.ListNode”


这有点令人困惑。

这是因为当您执行此操作时,
值[mod]
您正在访问一个
LinkedL
,因此,
Add
方法需要添加一个
ListNode

我认为混淆的是这里的
public LinkedL[]值在您的声明中


您在末尾添加了
[]
。因此,这意味着您正在声明一个
LinkedL
数组,而不仅仅是
LinkedL

values[mod]
的类型是
LinkedL
。因此,您需要添加一个
ListNode

首先,ListNode需要有一个构造函数,而不是
Insert
方法:

class ListNode<T>
{
    public T value { get; set; }
    public ListNode<T> next { get; set; }

    public ListNode(T newValue)
    {
        value = newValue;
    }
}

您的
LininkeL
在内部使用
ListNode
,因此您应该执行
LinkedL[]
而不是
LinkedL[]
您也不需要在
ListNode
上使用
Insert
方法,因为您只需直接设置
,当您设置值而不是插入值时,名称会令人困惑。这是否回答了您的问题?为什么
Add
方法需要
ListNode
?。这不是我想要的,甚至不是我期望的。@Noaztec它需要它,因为你告诉它
LinkedL
将包含
ListNode
的值,而你想告诉它将包含
int
的值,谢谢@juharr和sebrojas,我想我已经明白了
public void Add(T newVal)
{
    ListNode<T> node = new ListNode<T>(newVal);
    ...
}
public void Insert(int newValue)
{
   var mod = newValue % N;
   ListNode<int> node = new ListNode<int>(newValue);
   values[mod].Add(node);
}