这个关于的东西我看了几天了。一直没打看懂,我的领悟能力有点差,刚才突然明白了一点,的意思就是说:
类的泛型,只能是字句后面所写的接口或类。
这么说好像也有点不大明白,举个例子。
我有一个接口,如下:
1 ///2 /// 国籍的接口 3 /// 4 public interface INationality 5 { 6 string Nationality 7 { 8 set; 9 get; 10 } 11 string GetNationality(); 12 }
然后该接口有两个实现,如下:
1 ///2 /// 中国人 3 /// 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 ///22 /// 美国人 23 /// 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 ///2 /// 3 /// 4 ///5 public class PrintNationality 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 }
由于有字句的泛型约束,所以,创建PrintNationality<T>的对象时,T的类型只能是继承子INationality接口的类。
1 public class Program 2 { 3 static void Main(string[] args) 4 { 5 PrintNationality_c = new PrintNationality (); 6 PrintNationality _a = new PrintNationality (); 7 //PrintNationality
以上的代码运行结果:
Nationality:Chinese.Nationality:American.