约束
where T:struct 使用结构约束,类型T必须是值类型
where T: class 类约束指定,类型T必须是引用类型
where T: IFoo 必须执行接口IFoo
where T:Foo 必须派生于基类Foo
where T:new() 必须有一个默认构造函数
where T:U 约束可以指定,类型T1 派生于泛型类型T2。也称为裸类型约束
多个约束可以合并 where T:IFoo,new()
继承
静态成员
泛型接口
泛型方法
泛型委托
//泛型接口
//public sealed delegate void EventHandler<TeventArgs>(object sender,TeventArgs e) where TeventArgs:EventArgs;
public class DocumentManager<T> where T:IDocument //必须继承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 DisplayAllDocuments()
{
foreach (T doc in documentQueue)
{
Console.WriteLine(doc.title);
}
}
}
//public static
public interface IDocument
{
string title { get; set; }
string content { get; set; }
}
public class Document : IDocument
{
public string title { get; set; }
public string content { get; set; }
public Document()
{ }
public Document(string title, string content)
{
this.title = title;
this.content = content;
}
}
// 泛型类需要调用泛型上的方法,就必须添加约束
class Program
{
static void Main(string[] args)
{
DocumentManager<Document> dm = new DocumentManager<Document>();
dm.AddDocument(new Document("Title A", "Sample A"));
dm.AddDocument(new Document("Title B", "Sample B"));
dm.DisplayAllDocuments();
if (dm.IsDocumentAvailable)
{
Document d = dm.GetDocument();
Console.WriteLine(d.content);
}
//Node<int, string> node = new Node<int, string>();
//node.add(2, "11");
}
public static void Copy<R>(List<R> source, List<R> destination)
{
foreach (R obj in source)
{
destination.Add(obj);
}
}
}