C# 2.0 Generics
-----------------------
Visual Studio 2005 also introduces the next version of C#. C# 2.0 introduces generics, iterators, partial class definitions, nullable types, anonymous methods, the :: operator, static classes, accessor accessibility, fixed sized buffers (unsafe), friend assemblies, and #pragma warnings.
Visual Studio 2005 发行的同时,也带来了c# 的下一版本。C#2.0 给我们带来了泛型、迭代、泛型类定义、可空类型、匿名方法、::操作符、静态类、辅助访问、固定大小缓存(非安全)、友好编译、和编译警告指示。
---------------------------
Generic types allow for the reuse of code and enhanced performance for collection classes (due to boxing and unboxing issues).
泛型可以提高集合类的代码重用性和执行效率(由于装箱和坼箱操作消耗时间的内存)。
---------------------------
Generics are classes that are not type specific. For example, instead creating a Stack class for integers, another one for floats, you can create a generic class. The way this was done in the past was to create classes that just took objects. But, this lacks compile-time type checking. Everything is done at run-time.
泛型是通用的类。例如,你可以建立一个通用类来代替分别为 int类型、浮点类型编写 Stack类。这种方式在以前是通过使用对象(object)实现的,缺点是缺乏编译是的类型检测,所有bug要到运行是才发现。
--------------------------
// File: StackObject.cs
using System;
class Stack
{
object[] stack;
int top;
public Stack(int size)
{
stack = new object[size];
top = 0;
}
public object Pop()
{
return stack[--top];
}
public void Push(object v)
{
stack[top++] = v;
}
}
class Program
{
static void
Main
()
{
Stack stack = new stack(10);
// Performance hit, boxing!!!
stack.Push(5);
stack.Push(10);
// Another perf hit, unboxing!!!
int top = (int)stack.Pop();
}
}
By using generics, you can eliminate the boxing and unboxing.
通过使用泛型,你可以避免装箱和坼箱操作
-----------------------------
// File: StackGeneric.cs
using System;
class Stack<T>
{
T[] stack;
int top;
public Stack(int size)
{
stack = new T[size];
top = 0;
}
public T Pop()
{
return stack[--top];
}
public void Push(T v)
{
stack[top++] = v;
}
}
class Program
{
static void
Main
()
{
Stack<int> intStack = new Stack<int>(10);
intStack.Push(5);
intStack.Push(5);
int top = intStack.Pop();
}
}