<T> 吗?我看它好久了,一直不知道它是干嘛的。
与其写 ShowInt(int i) 和 ShowString(string s) 两个方法,不如写一个。
// T 是一个占位符,表示“某种类型”
public void Show(T msg)
{
Console.WriteLine("展示:" + msg);
}
// 调用时:
Show(100); // T 变成了 int
Show("哈"); // T 变成了 string
我们上一章用的 List<T> 就是最经典的泛型类。
// 一个通用的盒子,能装任何东西
class Box
{
public T Content;
public Box(T content)
{
Content = content;
}
}
// 造一个装剑的盒子
Box swordBox = new Box(new Sword());
// 造一个装药的盒子
Box pillBox = new Box(new Medicine());
如果 T 什么都能是,那它就什么都干不了(只能当 object 用)。我们可以给它加点限制。
// 这里的 T 必须是一个 class,且必须有一个无参构造函数
class Factory where T : class, new()
{
public T Create()
{
return new T(); // 因为有 new() 约束,所以可以 new
}
}
编写一个泛型方法 Swap<T>(ref T a, ref T b)。
它的作用是交换两个变量的值。
测试它是否既能交换整数,又能交换字符串。
static void Swap(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
// Main:
int x = 1, y = 2;
Swap(ref x, ref y); // x=2, y=1
string s1 = "A", s2 = "B";
Swap(ref s1, ref s2); // s1="B", s2="A"