zoukankan      html  css  js  c++  java
  • 泛型

    泛型:是CLR和编程语言提供的一种支持算法重用的特殊机制。

    类的一个参数(参数必须是一个类,不能是对象)也就是类的一个占位符参数。

    作用:将算法和数据结构完全分离开来,实现算法重用(重用类的结构)。避免装箱拆箱。类型安全,编译时会自动检测参数类型。

    //自定义泛型类

    public class MyTestG<T>

    {

    const int growth=1;

    int index=0;

    T[] arr;

    T[] arrNew;

    public MyTestG()

    {

    arr=new T[growth];

    }

    //新增元素

    public void Add(T num)

    {

    if(index>=arr.Length)

    {

    //扩容--创建扩容后大小的新数组

    arrNew=new T[arr.Length+growth];

    arr.CopyTo(arrNew,0);

    arr=arrNew;

    }

    arr[index]=num;

    index++;

    }

    //下标索引器取值

    public T this[int i]

    {

    get{return arr[i];}

    set{arr[i]=value;}

    }

    public int Count()

    {return arr.Length;}

    }

    //使用

    MyTestG<int> mtg=new MyTestG<int>();

    mtg.Add(1);

    mtg.Add(2);

    mtg.Add(3);

    for(int i=0;i<mtg.Count();i++)

    {

    MessageBox.Show(mtg[i].ToString());

    }

    //自定义泛型字典 Hashtable实现

    using System.Collections;

    public class MyDictionary<T,V>

    {

    Hashtable ht=new Hashtable();

    //索引器,通过key检索

    public V this[T key]

    {

    get{return (V)ht[key];}

    set{ht[key]=value;}

    }

    //添加元素

    public Add(T key,V value)

    {

    ht.Add(key,value);

    }

    //获得所有的键

    public ICollection<T> Keys()

    {

    List<T> keysList=new List<T>();

    foreach(T key in ht.Keys)

    {

    keysList.Add(key);

    }

    return keysList;

    }

    public int Count()

    {return ht.Count;}

    }

    //使用

    MyDictionary<string,string> mdic=new MyDictionary<string,string>();

    mdic.Add("a","q");

    mdic.Add("1","aa");

    mdic.Add("as","123");

    foreach(var item in mdic.Keys())

    {

    MessageBox.Show(mdic[item]);

    }

    泛型约束:

    在泛型类型或方法后面加default或where 然后跟类型或指定具体类型(具体可以查阅资料有详细说明)

    多个泛型约束

    class test<T,Tkey>:where T : class where Tkey : struct

  • 相关阅读:
    138.安全退出的异常,要用throw 尽量不用exit(0)
    137.CPP自带异常
    136.异常的多态,父类对象,传递子类的引用或指针(地址)
    135.异常与类继承
    134.异常类的处理
    133.throw机制 抛出类类型
    132.try throw catch介绍
    CF1039D You Are Given a Tree
    CF576E Painting Edges
    【模板】并查集维护生成树
  • 原文地址:https://www.cnblogs.com/buzhidaojiaoshenme/p/6821081.html
Copyright © 2011-2022 走看看