• 泛型


    泛型:是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

  • 相关阅读:
    当前网页调用其他网页
    保护自己的网页不被放入框架
    保护网页源码
    页面的后退、刷新、前进
    妙味——拖拽+碰撞+重力
    运行代码
    妙味——弹性运动
    IE css bug及解决方案参考
    妙味——布局转换的应用
    [LeetCode][JavaScript]Count Complete Tree Nodes
  • 原文地址:https://www.cnblogs.com/buzhidaojiaoshenme/p/6821081.html
Copyright © 2020-2023  润新知