c# 泛型
泛型是c#中一种代码重用技术。比如说两个模块功能相近,只是处理对象不同,一个是int,一个是float,这时使用通用参数可简化编程。
泛型与C++中模板机制类似,但没有模板复杂。比如c#不允许非类型模板参数:template <int i>{};
//泛型
using System;
using System.Collections;//ArrayList所在类库
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
public class Point
{
public T x, y;
public Point(T a,T b){
x = a; y = b;
}
public void show()
{
Console.Write("{0} {1}\n", x, y);
}
}
class Program
{
static void Main(string[] args)
{
Point
int_obj = new Point
(3,4);
Point
str_obj = new Point
("hi","hello"); int_obj.show(); str_obj.show(); Console.Read(); } } } /* 输出; * 3 4 * hi hello */
c#还提供类型参数约束。
类型参数 T 约束 | |
约束 | 说明 |
where T:struct | 必须为值类型 |
shere T:class | 必须为引用类型 |
shere T:new() | 类型参数必须具有无参数的公共构造函数。当与其他约束一起使用时,new()约束必须放最末 |
shere T:base_class_name | 必须是此类或其派生类 |
shere T:interface_name | 必须是此接口 |