如何在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);
}