C#中的泛型約束

來源:互聯網
上載者:User

C#中的泛型約束只支援顯示的約束,因為這樣才能保證C#中的型別安全,但顯示的約束並非是必須的,如果不加約束,泛型型別參數將只能訪問System.object類型中的公有方法。“顯示約束”由Where子句表達,可以指定“基類約束”、“介面約束”、“構造器約束”、“實值型別/參考型別約束”
/************基類約束*****************/
        class A
        {
            public void F1() { }
        }
        class B
        {
            public void F2() { }
        }
        class C<S, T>
            where S : A //S繼承自A
            where T : B //T繼承自B
        {
            //可以在類型為S的變數上調用F1,
            //可以在類型為T的變數上調用F2
        }

     /***********介面約束********************/
        interface IPrIntable
        {
            void PrInt();
        }
        interface IComparable<T> { int CompareTo(T v);}

        interface IkeyProvider<T> { T GetKey();}

        class Dictionary<K, V> where K:IComparable<K> where V: IPrIntable,IkeyProvider<K>
        {
            //可以在類型為K的變數上條用CompareTo,可以在類型為V的變數上調用PrInt和GetKey
        }

    /*************構造器約束************************/
        class A { public A() { } }

        class B { public B(int i) { } }

        class C<T> where T:new()
        {
          //可以在其中使用 T t=new T();
        }

        C<A> c = new C<A>();//可以;A有無參數的建構函式
        C<B> c = new C<B>();//不可以,B沒有無參數的建構函式

     /*************值/參考型別約束*********************/
        public struct A { }

        public class B { }

        class C<T> where T : struct
        {
           //T在這裡是一個實值型別
        }
        C<A> c = new C<A>(); //可以,A是一個實值型別
        C<B> c = new C<B>();//不可以,B是一個參考型別

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.