首页 / 软件开发 / C# / C#泛型秘诀(4)
C#泛型秘诀(4)2011-03-254.6 链表的实现问题您需要链表数据结构,这样就可以很容易地添加和删除元素。解决方案使用泛型LinkedList<T>类。下面的方法创建了一个LinkedList<T>类,并往链表对象中添加节点,然后使用了几种方法从链表节点中获得信息。public static void UseLinkedList()
{
// 创建一个LinkedList 对象.
LinkedList<TodoItem> todoList = new LinkedList<TodoItem>();
// 创建添加到链表内的TodoItem对象.
TodoItem i1 = new TodoItem("paint door", "Should be done third");
TodoItem i2 = new TodoItem("buy door", "Should be done first");
TodoItem i3 = new TodoItem("assemble door", "Should be done second");
TodoItem i4 = new TodoItem("hang door", "Should be done last");
// 添加项目.
todoList.AddFirst(i1);
todoList.AddFirst(i2);
todoList.AddBefore(todoList.Find(i1), i3);
todoList.AddAfter(todoList.Find(i1), i4);
// 显示所有项目.
foreach (TodoItem tdi in todoList)
{
Console.WriteLine(tdi.Name + " : " + tdi.Comment);
}
// 显示链表内的第二个节点的信息
Console.WriteLine("todoList.First.Next.Value.Name == " +
todoList.First.Next.Value.Name);
// 显示链表内最后一个节点的前一节点信息.
Console.WriteLine("todoList.Last.Previous.Value.Name == " +
todoList.Last.Previous.Value.Name);
}
这个方法的输出结果如下:buy door : Should be done first
assemble door : Should be done second
paint door : Should be done third
hang door : Should be done last
todoList.First.Value.Name == buy door
todoList.First.Next.Value.Name == assemble door
todoList.Last.Previous.Value.Name == paint door
下面是TodoItem类,它只简单地包含了两个字符串_name和_comment。public class TodoItem
{
public TodoItem(string name, string comment)
{
_name = name;
_comment = comment;
}
private string _name = "";
private string _comment = "";
public string Name
{
get { return (_name); }
set { _name = value; }
}
public string Comment
{
get { return (_comment); }
set { _comment = value; }
}
}