C#中的where泛型约束【转】
2011-12-01 16:12
375 查看
这个关于泛型约束的东西我看了几天了。一直没打看懂,我的领悟能力有点差,刚才突然明白了一点,泛型约束的意思就是说:
类的泛型,只能是where字句后面所写的接口或类。
这么说好像也有点不大明白,举个例子。
我有一个接口,如下:
然后该接口有两个实现,如下:
然后创建一个泛型类,带有泛型约束的类,如下:
由于有where字句的泛型约束,所以,创建PrintNationality<T>的对象时,T的类型只能是继承子INationality接口的类。
以上的代码运行结果:
http://luacloud.com/2011/where-generic-constraint.html
类的泛型,只能是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.
http://luacloud.com/2011/where-generic-constraint.html
相关文章推荐
- C# 泛型 WHERE 约束
- 关于C#中泛型类型参数约束(where T : class)
- C# 泛型类型约束 where
- 关于C#中泛型类型参数约束(where T : class)
- C# 泛型约束 xxx Where T:约束(二)
- C#中的where泛型约束中的new()
- C#中的where泛型约束中的new()构造函数约束
- c# where(泛型类型约束)
- c#泛型类型的约束条件where
- c# 泛型T类型参数T的约束where
- C# 泛型方法Where 约束
- 【C#】C#关键字-where(泛型类型约束)
- c# 泛型类型参数T的约束where
- C#中的where泛型约束中的new()构造函数约束
- C#中泛型约束(where)是什么?
- C#中的where泛型约束中的new()使用(转)
- C#中的where泛型约束
- where(泛型类型约束)(C# 参考)
- c#中的WHERE语句 ——where(泛型类型约束)
- C#中的where泛型约束