C#约束,泛型高级:泛型委托,泛型接口,泛型方法重载

1、值类型约束:将一个类型形参(T)限定为值类型。
值类型派生于System.ValueType类型。
值类型约束格式:where T:struct
eg、
public static void Main()
{
int a = 9;
func (a);
+
}
public static void func<T>(T t) where T :struct
{
Console.WriteLine (t);
}
2、引用类型约束:将一个类型形参限定为引用类型。引用类型:接口、类、委托、字符串、数组。
引用类型约束格式:where T:class
eg、
public static void Main()
{
string s="123";
func2 (s);
}
public static void func2<T>(T t) where T :class
{
Console.WriteLine (t);
}
3、构造函数约束:要求类型实参必须提供一个无参数的公有构造函数。
构造函数约束格式:where T:new()
Note:
(1)、new()约束可以与其他约束一起使用,但必须处于约束列表的末端
(2)、new()约束即使开发人员是用有参的构造函数构造的对象,类里也必须有一个无参的构造函数。
(3)、不可以同时使用new()约束和值类型约束。因为值类型都隐式的提供了一个无参的公共构造函数。就如定义接口时指定访问类型为public一样,编译器会报错,因为接口一定是public。
eg、
public static void Main()
{
A a = new A ();
func6 (a);
B b = new B (1);
func6 (b);
}
public static void func6<T>(T t)where T:new()
//类型T必须有无参的构造函数,有参数的会报错
{
Console.WriteLine (t);
}
class B
{
public B(int x){}
public B(){}
}
4、基类约束:意味着对于任意给定的基类约束,类型实参必须是基类本身或者派生于该基类的类。
基类约束格式:where T:基类名称
eg、
class A{}
class B:A{}
class C:A{}
public static void Main()
{
A a = new A ();
B b = new B ();
C c = new C ();
func4 (a);
func4 (b);
func4 (c);
}
public static void func4<T>(T t) where T:A
//必须为A或A的派生类,或者继承于A的派生类也可以。
{
Console.WriteLine (t);
}
5、接口约束:指对任何给定的接口约束,类型实参必须是接口本身或者实现了该接口的类,如果是派生于实现了该接口的类也可以。
接口约束格式:where T:接口名称  --> 可以用逗号分隔开指定的多个接口,若某个约束同时包含基类和接口,则需要指定基类列表,再指定接口列表。
eg、
interface Iprogram//接口
{
void show();
}
class D:Iprogram//实现接口的类
{
public void show()
{
Console.WriteLine ("I'm D!!!");
}
}
class E:D{}//派生于实现接口的类


public static void func5<T>(T t)where T:Iprogram
{
t.show ();
Console.WriteLine (t);
}
public static void Main()
{
D d = new D ();
func5 (d);
E e = new E ();
func5 (e);
}
6、组合约束:同一类型形参可以使用多个约束,要用逗号分隔开约束列表。
并且第一个约束必须是引用类型约束或者值类型约束,或者是基类约束。
不能在指定引用类型约束或值类型约束的同时,也指定基类约束。
然后之后是所有的接口约束,最后才能是new()约束。
7、泛型委托:实现了代码复用
eg、
class MainClass
{
public delegate void Mydelegate<T>(T a);//泛型委托:绑定了Add 方法
public static void Main()
{
//在泛型委托使用时必须指明具体类型,在泛型方法使用时也必须指明具体类型。
Mydelegate<int> d1 = new Mydelegate<int> (new Math ().Add<int>);
Mydelegate<string > d2 = new Mydelegate<string> (new Math ().Add<string>);
d1 (2);
d2 ("Hello");
}
}
class Math
{
public void Add<T>(T a)//泛型方法
{
Console.WriteLine(a) ;
}
}
8、泛型接口
eg、
interface Myinterface<T>
{
void print(T a);
}
class W:Myinterface<int>//用于打印整数
{
public void print(int a)
{
Console.WriteLine (a);
}
}
class Q:Myinterface<string>//用于打印字符串
{
public void print(string a)
{
Console.WriteLine (a);
}
}
class MainClass
{
public static void Main()
{
W w = new W ();
w.print (2);
Q q = new Q ();
q.print ("1234");
}
}
 9、泛型方法重载
eg、
class Node<T,V>
{
public T add(T a,V b)
{
return a;
}
public T add(V a,T b)
{
return b;
}
public int add(int a,int b)
{
return a + b;
}
}
如果V和T的类型都是int,则调用add方法时,会自动调用第三个方法,即返回a+b的值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值