C#进阶学习第十天

1.C#泛型编程

1.用T表示不确定的类型来作为一个占位符,等待在实例化时用一个实际的类型来代替。

 public class Vector<T>
{ private T[]  array;                  int main()
  private int size;                    { Vector<int>    a1 = new Vector<int> (5);
  public Vector(int n)                   Vector<string> a2 = new Vector<string> (5);                  
  {   array = new T[n];                  Vector<double> a3 = new Vector<double> (5);
	  size = 0;                          for循环赋值
  }                                      a1.add (i);
  public void add(T index)               a2.add ("hell" + i);
  {   array [size++] = index;            a3 [i] = i * 1.1;
  }                                    }
                                        
  public  T this[int i]
  {     get{ return array [i];}
	        set{ array [i] = value;} 
  }
}

特点:
1.类型安全,实例化int类型,就不能处理其它类型
2.无需装箱和拆箱
3.无需类型转换
2.系统提供的范型 list 引入using System.Collections.Generic;命名空间可直接使用
list容器每个元素都对应着一个整型下标

     List<int> a = new List<int> (5);
	 for (int i = 0; i <5; i++){   a.Add (i) ;  }
	 for (int i = 0; i < a.Count; i++){  Console.WriteLine (a[i]);  }     

3.系统提供的字典保存的数据是以键值对的形式存储的,两个范型参数:下标(键)的类型,元素(值)的类型
Dictionary容器每个元素(值)对应一个自定义类型的下标

     Dictionary<string ,int> a = new Dictionary<string, int> ();
	 for (int i = 0; i < 5; i++){ a.Add ("hello" + i, i); } 
	 for (int i = 0; i < 5; i++){Console.WriteLine (a["hello"+i]);}

1.字典的索引器写法

     public Dictionary<string ,News> mydir;
     public News  this[string index]   //返回的是值, 下标是键
     {
       get{ return mydir [index];}
	   set{ mydir [index] = value;}
     }

2.Stopwatch类用来统计时间

     Stopwatch aa = new Stopwatch ();
     aa.start();   aa.stop();
     TimeSpan ts = aa.Elapsed;
     Console.WriteLine ( ts.Seconds +"  "  +ts.Milliseconds);

2.泛型参数

开放泛型:没有指定泛型参数的泛型 Type p = typeof(List<>); //typeof 类型的详细信息

封闭泛型:指定了泛型参数的泛型 Type a = typeof(List); //Type 保存类型的详细信息的类
Console.WriteLine (p.ContainsGenericParameters); // true
Console.WriteLine (a.ContainsGenericParameters); // false

泛型类
1.不同的封闭泛型中都有自己的静态成员
2.每个封闭泛型类型都有一个静态构造函数
泛型方法

    public static void print<T>(T s)  { Console.WriteLine (s); }  
    int main()
    {  print<int> (4); 
          print ("hello");//泛型参数可以省略,根据参数自动确认类型
    }   
    //public static T add<T>(T a, T b){ return a+b}
    //报错!T是一个不确定的类型,不能直接对T类型的变量直接操作
    //public void tun<T,V>(T a,V b){console.writeline(“{0} {1}”,a,b);}

猜你喜欢

转载自blog.csdn.net/JingDuiTell/article/details/88736376