(*) where
用来限制泛型的类型。
where T : struct 可简单理解为只允许值类型(其实是其继承链中必须有值类型)
where T : class 可简单理解为只允许引用类型(其实是其继承链中必须有引用类型)
where T : new() 所有值类型OK,如果是引用类型则必须支持用无参构造函数实例化。(有多个where约束时,new()必须在末尾)
where T : 类名 必须是某个类的子类
where T : 接口名 必须实现了某个接口
多个where限制之间用空格隔开,例如where T : class IDrawable new(),同时满足三种约束
where不支持运算符重载,例如where T : operator +是不允许的,所以不能在函数体内用到+-等运算符,我觉得这是C#应该改进的地方。
(*) 继承泛型基类,实现泛型接口,都必须把类型确定下来
例如:public class BasicMath : IBinaryOperation<int>{...}
(*) 泛型委托
就是连类型都不顾的委托,这玩意有用吗?
class Program
{
public delegate void MyDelegate<T>(T a, T b);
static void ShowSum(int a, int b) { Console.WriteLine(a + b); }
static void ShowDifference(int a, int b) { Console.WriteLine(a - b); }
static void Concatenate(string a, string b) { Console.WriteLine(a + b); }
static void Main()
{
MyDelegate<int> ProceedInteger = ShowSum;
ProceedInteger += ShowDifference;
ProceedInteger(1, 2);
MyDelegate<string> ProceedDouble = Concatenate;
ProceedDouble("a", "b");
}
}
{
public delegate void MyDelegate<T>(T a, T b);
static void ShowSum(int a, int b) { Console.WriteLine(a + b); }
static void ShowDifference(int a, int b) { Console.WriteLine(a - b); }
static void Concatenate(string a, string b) { Console.WriteLine(a + b); }
static void Main()
{
MyDelegate<int> ProceedInteger = ShowSum;
ProceedInteger += ShowDifference;
ProceedInteger(1, 2);
MyDelegate<string> ProceedDouble = Concatenate;
ProceedDouble("a", "b");
}
}
浙公网安备 33010602011771号