zoukankan      html  css  js  c++  java
  • 范型的用法大全

    1: 创建一个范型类MyList.cs
    public class MyList<T>
     {
      private static int objCount = 0;

      public int Count
      {
         get
          {
             return objCount;
            }
      }

        public MyList()
        {
            objCount++;
        }

     }

    2:调用范型类MyList.cs
     public void MyListShow()
        {
          //调用范型类
       MyList<int> myIntList = new MyList<int>();
      MyList<int>  myIntList2 = new MyList<int>();
      MyList<double> myDoubleList = new MyList<double>();

      Response.Write(myIntList.Count.ToString());
          Response.Write(myIntList2.Count.ToString());
          Response.Write(myDoubleList.Count.ToString());
        }

    3:范型方法的使用

        public static void Copy<T>(List<T> source, List<T> destination)
      
        {
         foreach (T obj in source)
         {
        destination.Add(obj);
         }
       }


        public void CopyList()
        {
        List<int> lst1 = new List<int>();
      lst1.Add(2);
      lst1.Add(4);
        List<int> lst2 = new List<int>();
      Copy(lst1,lst2);//调用范型方法
        for (int i = 0; i < lst2.Count; i++)
        {
        Response.Write(lst2[i].ToString());//输出数据 }
        }
       }

    4:范型约束的比较
     //范型约束 比较
        public static T Max<T>(T op1, T op2) where T : IComparable //必须继承IComparable 
       {
        if (op1.CompareTo(op2)<0)
           return op1;
        return op2;
       }

     Response.Write(Max<int>(4, 2).ToString());//调用Max方法输出数据

    5:范型与反射
     public void TypeShow()
        {
        MyList<int> obj1 = new MyList<int>();
        MyList<double> obj2 = new MyList<double>();
      Type type1 = obj1.GetType();
      Type type2 = obj2.GetType();

        Response.Write("obj1’s Type");
        Response.Write(type1.FullName);
        Response.Write(type1.GetGenericTypeDefinition().FullName);
        Response.Write("obj2’s Type");
        Response.Write(type2.FullName);
        Response.Write(type2.GetGenericTypeDefinition().FullName);
     }
    6:范型的继承关系

    例上面的MyList.cs范型类   再建一个普通类MyList1.cs

    //public class MyList1<T> : MyList<int>//此时有效 // 一个封闭结构的泛型进行派生
    //public class MyList1<T> : MyList<T>//此时有效  一个开放结构的泛型进行派生
    //public class MyList1 : MyList<T>此时是无效的 不能继承 会报错    //称作开放结构的泛型
    public class MyList1 : MyList<int>//此时是有效的   //称作封闭结构的泛型
    {
     public MyList1()
     {
     }
    }



  • 相关阅读:
    Python+SparkStreaming+kafka+写入本地文件案例(可执行)
    Python安装pycurl失败,及解决办法
    Linux screen用法简介
    [算法]数组中求出下标不连续的任意个数,使得和最大
    消息队列小结
    [算法]计算全排列组合数
    [数据结构]A*寻路算法
    [数据结构]最大流之Ford-Fulkerson算法
    [数据结构]最小生成树算法Prim和Kruskal算法
    [数据结构]迪杰斯特拉(Dijkstra)算法
  • 原文地址:https://www.cnblogs.com/xiaobaigang/p/836176.html
Copyright © 2011-2022 走看看