C# 2.0 泛型

原文阅读!Dan Vallejo's WebLog!

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();
    }
}

   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值