泛型

泛型有泛型接口、泛型类、泛型方法、泛型事件和泛型委托。
 
泛型类声明
[访问修饰][安全检查修饰][结构修饰][继承修饰]类名<T>[:][基类],[接口][WHERE 泛型约束]
 
泛型方法声明
[访问修饰][安全检查修饰][继承修饰][返回类型]方法名<T>([扩展修饰][参数修饰][参数类型]参数名)
 
泛型约束
 
1、派生约束
在 C# 2.0 中,可以使用 where 保留关键字来定义约束。在一般类型参数中使用 where 关键字,后面跟一个派生冒号,以指示编译器该一般类型参数实现了特定接口。例如,以下为实现 LinkedList 的 Find() 方法所必需的派生约束:
public class LinkedList where K : IComparable
{
T Find(K key)
{
Node current = m_Head;
while(current.NextNode != null)
{
if(current.Key.CompareTo(key) == 0)

break;
else

current = current.NextNode;
}
return current.Item;
}
//Rest of the implementation
}
 
2、构造函数约束
C# 允许约束一般类型参数,以使其必须支持公共默认构造函数。这是使用 new() 约束完成的。

class Node where T : new()
{
public K Key;
public T Item;
public Node NextNode;
public Node()
{
Key = default(K);
Item = new T();
NextNode = null;
}
}
可以将构造函数约束与派生约束组合起来,前提是构造函数约束出现在约束列表中的最后:
public class LinkedList where K : IComparable,new() {...}

 
3、引用/值类型约束

可以使用 struct 约束将一般类型参数约束为值类型(例如,int、bool 和 enum),或任何自定义结构:
public class MyClass where T : struct {...}

同样,可以使用 class 约束将一般类型参数约束为引用类型(类):
public class MyClass where T : class {...}

转载于:https://www.cnblogs.com/gzwrf/archive/2009/03/19/1416657.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值