C#中的where泛型約束

來源:互聯網
上載者:User

這個關於泛型約束的東西我看了幾天了。一直沒打看懂,我的領悟能力有點差,剛才突然明白了一點,泛型約束的意思就是說:

類的泛型,只能是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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.