C# 自定义泛型类,并添加约束
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GenericExam
{
class Program
{
static void Main(string[] args)
{
var dm = new DocumentManager<Document>();
dm.AddDocument(new Document("Title A","Content A"));
dm.AddDocument(new Document("Title B","Content B"));
dm.DisplayAllDocument();
if (dm.IsDocumentAvailable)
{
Document d = dm.GetDocument();
Console.WriteLine(d.Title);
}
Console.Read();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GenericExam
{
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(string title, string content)
{
this.Title = title;
this.Content = content;
}
}
public class DocumentManager<T> where T : IDocument
{
public 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);
lock (this)
{
doc = DocumentQueue.Dequeue();
}
return doc;
}
public void DisplayAllDocument()
{
foreach (T doc in DocumentQueue)
{
Console.WriteLine(((IDocument)doc).Title);
}
}
}
}