这个关于泛型约束的东西我看了几天了。一直没打看懂,我的领悟能力有点差,刚才突然明白了一点,泛型约束的意思就是说:
类的泛型,只能是where字句后面所写的接口或类。
这么说好像也有点不大明白,举个例子。
我有一个接口,如下:
1 ///<summary>
2 /// 国籍的接口
3 ///</summary>
4 public interface INationality
5 {
6 string Nationality
7 {
8 set;
9 get;
10 }
11 string GetNationality();
12 }
然后该接口有两个实现,如下:
1 ///<summary>
2 /// 中国人
3 ///</summary>
4 public class Chinese : INationality
5 {
6 private string _Nationality;
7 public string Nationality
8 {
9 set
10 {
11 _Nationality = value;
12 }
13 }
14
15 public string GetNationality()
16 {
17 return string.IsNullOrEmpty(_Nationality) ? "Default." : _Nationality;
18 }
19 }
20
21 ///<summary>
22 /// 美国人
23 ///</summary>
24 public class American : INationality
25 {
26 private string _Nationality;
27 public string Nationality
28 {
29 set { _Nationality = value; }
30 }
31
32 public string GetNationality()
33 {
34 return string.IsNullOrEmpty(_Nationality) ? "Default." : _Nationality;
35 }
36 }
然后创建一个泛型类,带有泛型约束的类,如下:
1 ///<summary>
2 ///
3 ///</summary>
4 ///<typeparam name="T"></typeparam>
5 public class PrintNationality<T> where T : INationality, new()
6 {
7 T item = new T();
8 public void Print()
9 {
10 Console.WriteLine(string.Format("Nationality:{0}", item.GetNationality()));
11 }
12 }
由于有where字句的泛型约束,所以,创建PrintNationality<T>的对象时,T的类型只能是继承子INationality接口的类。
1 public class Program
2 {
3 static void Main(string[] args)
4 {
5 PrintNationality<Chinese> _c = new PrintNationality<Chinese>();
6 PrintNationality<American> _a = new PrintNationality<American>();
7 //PrintNationality<Object> _o = new PrintNationality<Object>(); 此句是错误的,因为泛型类型必须是继承自INationality接口的类
8 _c.Print();
9 _a.Print();
10 Console.ReadKey();
11 }
12 }
以上的代码运行结果:
Nationality:Chinese. Nationality:American.