-IDocument.cs(定义一个接口)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
public interface IDocument
{
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。该约束也称为裸类型约束