zoukankan      html  css  js  c++  java
  • 读<<CLR via C#>> 详谈泛型

    1,什么是泛型?
      答:泛型是类型的模板,类型是实例(对象)的模板。C#提供了5种泛型:类,接口,委托,结构和方法。

      2,使用泛型有什么好处?
      答:继承实现的是"代码重用",而泛型实现的是另一种形式的代码重用,即"算法重用"。总结起来有以下优点:
        1> 提高代码的可重用性。
        2> 编译时的类型安全性。当使用一个不兼容的类型的时候,会在编译时就报错,而不用等到运行时再报错,提高了类型安全性。
        3> 更佳的性能。当操作值类型实例的时候,使用泛型会减少值类型的装箱,这样在程序的托管堆上内存分配更少,垃圾回收也没那么频繁,从而能提高程序的性能。

    使用泛型类实例

      下面是一个使用泛型来实现栈的实例,Main方法定义了两个变量,stackInt和stackString。使用int和string作为类型实参来创建这两个构造类型的实例(对象)。代码如下:

     1 namespace GenericDemo1
     2 {
     3     //定义一个泛型类
     4     class MyStack<T>
     5     {
     6         T[] StackArray;//声明数组引用
     7         int StackPointer = 0;
     8 
     9         const int MaxStack = 10;
    10         bool IsStackFull//只读属性
    11         {
    12             get 
    13             {
    14                 return StackPointer >= MaxStack;
    15             }
    16         }
    17         bool IsStackEmpty
    18         {
    19             get
    20             {
    21                 return StackPointer <= 0;
    22             }
    23         }
    24 
    25         public void Push(T x)//入栈
    26         {
    27             if (!IsStackFull)//栈未满
    28             {
    29                 StackArray[StackPointer++] = x;
    30             }
    31         }
    32 
    33         public T Pop()//出栈
    34         { 
    35             return (!IsStackEmpty)?StackArray[--StackPointer]:StackArray[0];
    36         }
    37 
    38         public MyStack()//构造函数
    39         { 
    40             StackArray=new T[MaxStack];//实例化数组对象
    41         }
    42 
    43         public void Print()
    44         {
    45             for (int i = StackPointer - 1; i >= 0; i--)
    46             {
    47                 Console.WriteLine("Value: {0}",StackArray[i]);
    48             }
    49         }
    50     }
    51 
    52     class Program
    53     {
    54         static void Main(string[] args)
    55         {
    56             var stackInt = new MyStack<int>();//实例化构造类型,等价于MyStack<int> stackInt=new MyStack<int>();
    57             var stackString = new MyStack<string>();
    58 
    59             stackInt.Push(3);//调用Push方法,注意此时类型实参为int
    60             stackInt.Push(5);
    61             stackInt.Push(7);
    62             stackInt.Print();
    63 
    64             stackString.Push("A");//调用Push方法,注意此时类型实参为string
    65             stackString.Push("B");
    66             stackString.Print();
    67 
    68             Console.ReadKey();
    69 
    70         }
    71     }
    72 }

    程序输出结果为:

  • 相关阅读:
    SpringBoot入门
    VUE 监听局部滚动 设置ICON的位置跟随
    手机端页面调试工具-vconsole使用
    js获取字符串字节的位数
    判断数据为[] {} /空数组或空对象
    Vue axios 上传图片
    Vue触发input选取文件点击事件
    腾讯地图添加多个Marker
    VUE-CLI 设置页面title
    小程序wxml文件引用方式
  • 原文地址:https://www.cnblogs.com/0515offer/p/4242082.html
Copyright © 2011-2022 走看看