C#语言学习之旅(8)--泛型
时间:2011-05-31 来源:jackdesk
泛型是由2.0引进来的,有了泛型,就不再使用object类了。泛型相当于c++中的模板,泛型是C#语言的一个结构而且是CLR定义的。泛型的最大优点就是提高了性能,减少了值类型和引用类型的拆箱和装箱。
8.1 创建泛型类
创建泛型类和定义一般类类似,只是要使用泛型类型声明。下面给出例子:
泛型简单demo using System;using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace GenericDemo
{
//泛型
public class LinkedListNode<T>
{
public LinkedListNode(T value)
{
this.value = value;
}
private T value;
public T Value
{
get { return value; }
}
private LinkedListNode<T> next;
public LinkedListNode<T> Next
{
get { return next; }
internal set { next = value; }
}
private LinkedListNode<T> prev;
public LinkedListNode<T> Prev
{
get { return prev; }
internal set { prev = value; }
}
}
public class LinkedList<T> : IEnumerable<T>
{
private LinkedListNode<T> first;
public LinkedListNode<T> First
{
get { return first; }
}
private LinkedListNode<T> last;
public LinkedListNode<T> Last
{
get { return last; }
}
//添加
public LinkedListNode<T> AddLast(T node)
{
LinkedListNode<T> newNode = new LinkedListNode<T>(node);
if (first == null)
{
first = newNode;
last = first;
}
else
{
last.Next = newNode;
last = newNode;
}
return newNode;
}
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
LinkedListNode<T> current = first;
while (current != null)
{
yield return current.Value;
current = current.Next;
}
}
#endregion
#region IEnumerable Members
//返回枚举值
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
class Program
{
static void Main(string[] args)
{
//所使用泛型
LinkedList<int> list2 = new LinkedList<int>();
list2.AddLast(3);
list2.AddLast(5);
list2.AddLast(7);
foreach (int i in list2)
{
Console.WriteLine(i);
}
}
}
}
8.2 泛型类的特性
a.默认值
相关阅读 更多 +