1.默认值default
default关键字根据上下文可以有多种含义。在泛型中,根据泛型类型是引用类型还是值类型,泛型default用于将泛型类型初始化为null或0.
2.约束
如果泛型类需要调用泛型类型中的方法,必须添加约束。where字句指定接口,where字句的一个重要限制就是,不能定义必须由泛型类型实现的运算符。运算符不能再借口中定义。在where子句中,只能定义基类、借口和默认构造函数。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication3
{
public class DocumentManager<TDocument>where TDocument:IDocument
{
private readonly Queue<TDocument> documentQueue = new Queue<TDocument>();
public void AddDocument(TDocument doc)
{
lock (this)
{
documentQueue.Enqueue(doc);
}
}
public bool IsDocumentAvailable
{
get { return documentQueue.Count > 0; }
}
public TDocument GetDocument()
{
TDocument doc = default(TDocument);
lock (this)
{
doc = documentQueue.Dequeue();
}
return doc;
}
public void DisplayAllDocuments()
{
foreach (TDocument doc in documentQueue)
{
Console.WriteLine(doc.Title);
}
}
}
public interface IDocument
{
string Title { get; set; }
string Content { get; set; }
}
public class Document : IDocument
{
public Document()
{
}
public Document(string title,string content)
{
this.Title = title;
this.Content = content;
}
public string Title{get;set;}
public string Content{get;set;}
}
public class AA
{
public static void Main()
{
var 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);
}
}
}
}
3.继承
泛型类型可以实现泛型接口,也可以派生自一个类。泛型类可以派生自泛型基类,要求是必须重复接口的泛型类型或者指定基类的类型。
例如:
public class Base<T>
{
}
public class Derived<T> :Base<string>
{
}
public class Derived<T> :Base<T>
{
}
4.静态成员
泛型类的静态成员只能在类的一个实例中共享。例如
public class StaticDemo<T>
{
public static int x;
}
使用时
StaticDemo<string>.x = 4;
StaticDemo<int>.x = 5;
Console.WriteLine(StaticDemo<string>.x);//4