-IDocument.cs(定義一個接口)ide
using System;函數
using System.Collections.Generic;this
using System.Linq;spa
using System.Text;對象
using System.Threading.Tasks;接口
namespace ConsoleApplication3隊列
{get
public interface IDocumentstring
{it
string Title { get; set; }//文本標題
string Content { get; set; }//文本內容
}
}
-----------------------------------Document.cs(用於實現接口的一個類)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
public class Document : IDocument//實現了接口IDocument的類
{
private string _title;
private string _content;
public string Title
{
get
{
return _title;
}
set
{
_title = value;
}
}
public string Content
{
get
{
return _content;
}
set
{
_content = value;
}
}
public Document(string title,string content)
{
this.Title = title;
this.Content = content;
}
}
}
-----------------------------------DocumentManage.cs(泛型類)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace ConsoleApplication3
{
public class DocumentManage<TDocuemnt>
where TDocuemnt : IDocument //約束:該類必須實現了IDocuemnt的接口
{
//實例化一個存放對象的隊列
private readonly Queue<TDocuemnt> documentQuery = new Queue<TDocuemnt>();
public void AddDocument(TDocuemnt t)//添加對象到documentQuery隊列中
{
documentQuery.Enqueue(t);
}
public bool IsADocumentAvailable { get { return documentQuery.Count > 0; } }//判斷documentQuery隊列中有沒有值
public void DisplayAllDocuments()//查詢全部的對象
{
foreach (TDocuemnt t in documentQuery)
{
Console.WriteLine(((IDocument)t).Title);
Console.ReadKey();
}
}
}
}
-----------------------------------主程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
DocumentManage<Document> dm = new DocumentManage<Document>();
dm.AddDocument(new Document("標題1", "內容1"));
dm.AddDocument(new Document("標題2", "內容2"));
if (dm.IsADocumentAvailable)
{
dm.DisplayAllDocuments();//輸出標題1,標題2
}
}
}
}
============================================================
where T:struct 對於結構的約束,類型必須是值類型
where T:class 類約束指定的類型必須是引用類型
where T:IFoo 指定的類型T必須實現接口IFoo
where T:Foo 指定的類型T必須派生自基類Foo
where T:new() 指定一個構造函數約束,指定類型T必須有一個默認的構造函數
where T1:T2 這個約束也能夠指定,類型T1派生自泛型類型T2。該約束也稱爲裸類型約束