我正在尝试在Linux上使用monoDevelop用C#写一个自定义的LinkedList类,只为了测试和学习。以下代码从来没有编译过,我不知道为什么!它甚至没有告诉我哪里出了问题。它只是说:“错误:编译器似乎已经崩溃。请检查构建输出面板以获取详细信息。”当我去检查输出面板时,它也没有什么帮助:
未处理的异常:System.ArgumentException:指定的字段必须在泛型类型定义中声明。
参数名:字段
我该怎么办?
我该怎么办?
using System;
using System.Text;
using System.Collections.Generic;
namespace LinkedList
{
public class myLinkedList<T> : IEnumerable<T>
{
//List Node class
//===============
private class ListNode<T>
{
public T data;
public ListNode<T> next;
public ListNode(T d)
{
this.data = d;
this.next = null;
}
public ListNode(T d, ListNode<T> n)
{
this.data = d;
this.next = n;
}
}
//priavte fields
//===============
private ListNode<T> front;
private int size;
//Constructor
//===========
public myLinkedList ()
{
front = null;
size = 0;
}
//public methods
//===============
public bool isEmpty()
{
return (size == 0);
}
public bool addFront(T element)
{
front = new ListNode<T>(element, front);
size++;
return true;
}
public bool addBack(T element)
{
ListNode<T> current = front;
while (current.next != null)
{
current = current.next;
}
current.next = new ListNode<T>(element);
size++;
return true;
}
public override string ToString()
{
ListNode<T> current = front;
if(current == null)
{
return "**** Empty ****";
}
else
{
StringBuilder sb = new StringBuilder();
while (current.next != null)
{
sb.Append(current.data + ", ");
current = current.next;
}
sb.Append(current.data);
return sb.ToString();
}
}
// These make myLinkedList<T> implement IEnumerable<T> allowing
// a LinkedList to be used in a foreach statement.
public IEnumerator<T> GetEnumerator()
{
return new myLinkedListIterator<T>(front);
}
private class myLinkedListIterator<T> : IEnumerator<T>
{
private ListNode<T> current;
public virtual T Current
{
get
{
return current.data;
}
}
private ListNode<T> front;
public myLinkedListIterator(ListNode<T> f)
{
front = f;
current = front;
}
public bool MoveNext()
{
if(current.next != null)
{
current = current.next;
return true;
}
else
{
return false;
}
}
public void Reset()
{
current = front;
}
public void Dispose()
{
throw new Exception("Unsupported Operation");
}
}
}
}
Dispose
方法会被foreach
循环调用,因此最好不要在其中抛出异常。 - MagnusLinkedList<T>
内部的Node<T>
不应该是泛型;泛型类型参数是继承的 - 这可以直接使用Node
。编译器会警告你: "类型参数'T'与外部类型 'LinkedList.myLinkedList <T>' 的类型参数名称相同"。 - Marc Gravell