C#泛型

來源:互聯網
上載者:User

標籤:

泛型型別用<>來聲明的,允許用任意類型代替


1、命名規範<T..>


a、泛型型別的名稱用字母T作為首碼(但不強制,只是一個約定俗成而已)
b、如果沒有特殊要求,泛型型別允許用任意類替代;如果只使用了一個泛型型別,就可以用字元T作為泛型型別的名稱
public class List<T>{}
c、如果泛型型別有特定的要求,如它必須實現一個介面或者派生自某一個基類,或者使用了兩個或多個泛型型別,就應給泛型型別使用描述性的名稱
public delegate void EventHandler<TEventArgs>(objct sender,TEventArgs e)
public class SortedList<Tkey,Tvalue>{}


2、定義泛型型別約束


a、不能吧null賦予泛型型別,通過default關鍵字
where T:struct-->對於結構約束,類型T必須是實值型別
where T:class-->類約束,類型T必須是參考型別
where T:IBase-->介面約束,類型T必須實現介面IBase
where T:BaseClass-->類繼承約束,類型T必須派生自基類BaseClass
where T:new()-->建構函式約束,類型T必須有一個公用的無參數的建構函式
where T1:T2-->類型T1不行派生自類型T2

E.G

public class DocumentManager<T> where T:IDocument
{
private readonly Queue<T> documentQueue = new Queue<T>();

public void AddDocument(T Doc)
{
lock (this)
{
documentQueue.Enqueue(Doc);
}
}
public bool IsDocumentAvailable
{
get { return documentQueue.Count > 0; }
}
public T GetDocument()
{
T doc = default(T);//通過default關鍵字將null賦予參考型別,將0賦予實值型別;
lock (this)
{
doc = documentQueue.Dequeue();
}
return doc;
}
public void DisplayAllDocument()
{
foreach (T doc in documentQueue)
{
string title = doc.Title;
}
}
}

public interface IDocument
{
string Title { get; set; }
string Content { get; set; }
}

public class Document:IDocument
{
public Document() { }

public Document(string title, string content)
{
Title = title;
Content = content;
}
public string Title { get; set; }
public string Content { get; set; }
}
3、泛型介面
public interface IComparable<in T>
{
int CompareTo(T other)
}


4、泛型結構
5、泛型方法


void Swap<T>(ref T x,ref T y)
{
T Temp;
Temp=x;
x=y;
y=Temp;
}
//調用
int i=9,j=8;
Swap<int>(i,j);


6、泛型委派


public delegate void mydelegate<in sdele>(sdele obj);

C#泛型

聯繫我們

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