泛型类的功能:默认值、约束、继承、静态成员 。以从队列中读取文档为例
泛型继承:子类和基类泛型类型一致或指定基类的泛型类型
泛型的静态成员: 只能类的一个实例中共享
public class StaticDemo<T> { public static int x; } public void test() { StaticDemo<string>.x = 4; StaticDemo<int>.x = 5; Console.WriteLine(StaticDemo<string>.x); //输出4 Console.WriteLine(StaticDemo<int>.x); //输出5 }
文档接口(IDocument)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ListFunction { public interface IDocument { /// <summary> /// 文章标题 /// </summary> string Title { get; set; } /// <summary> /// 文章内容 /// </summary> string Content { get; set; } } }
文档类(Document)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ListFunction { public class Document:IDocument { /// <summary> /// 文章标题 /// </summary> public string Title { get; set; } /// <summary> /// 文章内容 /// </summary> public string Content { get; set; } public Document() { } public Document(string title, string content) { this.Title = title; this.Content = content; } } }
文档管理类(DocumentManager)泛型默认值、约束
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ListFunction { /// <summary> /// TDocument必须实现IDocument接口(泛型约束) /// </summary> /// <typeparam name="TDocument"></typeparam> public class DocumentManager<TDocument> where TDocument:IDocument { private readonly Queue<TDocument> documentQueue = new Queue<TDocument>(); /// <summary> /// 添加一个文档到队列尾 /// </summary> /// <param name="doc"></param> public void AddDocument(TDocument doc) { lock (this) //单线程(个人理解、无依据) { documentQueue.Enqueue(doc); //添加到结尾处 } } /// <summary> /// 队列不为空返回true /// </summary> public bool IsDocumentAvailable { get { return documentQueue.Count > 0; } } /// <summary> /// 获取文档(泛型默认值) /// </summary> /// <returns></returns> public TDocument GetDocument() { TDocument doc = default(TDocument); //将泛型类型初始化为null或0 lock (this) { doc = documentQueue.Dequeue(); //移除并返回位于 System.Collections.Generic.Queue<T> 开始处的对象。 } return doc; } /// <summary> /// 显示所有文档标题 /// </summary> public void DisplayAllDocument() { foreach (TDocument doc in documentQueue) { Console.WriteLine(((IDocument)doc).Title); Console.WriteLine(((IDocument)doc).Content); } } } }
测试类
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ListFunction { class Program { static void Main(string[] args) { var dm = new DocumentManager<Document>(); dm.AddDocument(new Document("Title A","Sample A")); dm.AddDocument(new Document("Title B", "Sample B")); dm.DisplayAllDocument(); if (dm.IsDocumentAvailable) { Document d = dm.GetDocument(); Console.WriteLine(d.Content); } } } }
要么忍,要么狠,要么滚!