泛型 17_9_5

2017-09-05  本文已影响0人  妈妈说喝牛奶能长个

泛型:类型作为参数进行传递

using System.Collections.Generic; //引入泛型命名空间

public static T Swap<T>(ref T a,ref T b){                       //定义什么类型 T就是什么类型的参数

            T temp = a;                                                           //交换外界传入的a 和 b

            a = b;

             b = temp;

}

int x = 2, y = 3;

Swap<int>(ref x,ref y);                    //x 和 y 必须是相同类型

floatt z =3.0f,s = 5.0f;

Swap<float>(ref z,ref s);

public static U Add<U,T>(U a,T b){                      //返回值类型为U

            return a;                                          //return U 类型的值

}

public static bool IsBigger<U> (U a,U b)where U:Comparable{          //限制写在参数之后 大括号之前

            return a.CompareTo(b)>0;

}

泛型常用的约束类型:

1. where T:struct :表示泛型T是值类型(小数,整数,char,bool,

struct)

2. where T:class :表示泛型T是引用类型

3. where T:new() :表示这个泛型具有一个无参数的构造方法,如果有多个约束,new()必须放在最后

4. where T:基类名 :表示这个泛型是该基类或者其派生类

5. where T:接口名 :表示泛型是实现了该接口的类型

上一篇 下一篇

猜你喜欢

热点阅读