[CSharp]C#2.0 銳利體驗系列課程 (1):泛型程式設計-學習筆記

來源:互聯網
上載者:User

問題:下面的定義中,哪個是錯誤的
1 class C<U,V>{}
2 class D:C<string,int>{}
3 class E<U,V>:C<U,V>{}
4 class F<U,V>:C<string,int>{}
5 class G:C<U,V>{}

解釋
1 泛型定義
2 D是普通類,C是執行個體化的泛型類垿IMG src="http://www.cnblogs.com/blog/smile19.gif">
3 E是子泛型型別,C是基泛型型別,C使用了子的泛型參敿IMG src="http://www.cnblogs.com/blog/smile19.gif">
4 F是泛垿C已經執行個體匿IMG src="http://www.cnblogs.com/blog/smile19.gif">
5 G是類,C是泛型類垿IMG src="C:\Program Files\BlogJet\Data\Smiles\smile20.gif">

注釋
可以在基類中包含泛型型別的聲明。但是注意:基類如果是泛型類,它的型別參數要麼已執行個體化,要麼來源於子?/FONT>

————————

泛型型別的成?FONT>

class C<V>{
    public V f1;     // 聲明f1
    public D<V> f2;  // 引用其它泛型型別來定義成員f2
    public C(V x){   // 方法
        this.f1 = x;
    }
}

————————-

泛型介面

定義方式入泛類型的定義一栿BR>interface IList<T>{
    T{} MethodA();
}
interface IDictionary<K,V>{
    void MethodB(K k , V v);
}

class List<T> : IList<T> , IDictionary<int,T>
{
    public T[] MethodA(){}
    public void MethodB(int i,T t){}
}

—————————-

泛型方法

public class Finder{
    public static int Find<T> ( T[] items , T item )
    {
        for(int i;i<items.Length;i++){
            if(items[i].Equals(item){return i;}
        }
    }
}

——————————

泛型方法的重?FONT>

class c{
    void F<T>(int x);
    void F(int x);
    public abstract T F<T,U>(T t,U u) where U:T;
}

重寫
class cc : c{
    public override X F<X,Y>(X x,Y y){}
}

-----------------

基類約束

class A{public void F1(){...}}
class B{public void F2(){...}}

class C<S,T>
where S: A
where T: B
{
    // 可以在類型S上調用F1方法
    // 可以在類型B上調用F2方法
    ...
}

相關文章

聯繫我們

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