C#泛型

泛型类型用<>来声明的,允许用任意类型代替


1、命名约定<T..>


a、泛型类型的名称用字母T作为前缀(但不强制,只是一个约定俗成而已)
b、如果没有特殊要求,泛型类型允许用任意类替代;如果只使用了一个泛型类型,就可以用字符T作为泛型类型的名称
public class List<T>{}
c、如果泛型类型有特定的要求,如它必须实现一个接口或者派生自某一个基类,或者使用了两个或多个泛型类型,就应给泛型类型使用描述性的名称
public delegate void EventHandler<TEventArgs>(objct sender,TEventArgs e)
public class SortedList<Tkey,Tvalue>{}


2、定义泛型类型约束


a、不能吧null赋予泛型类型,通过default关键字
where T:struct-->对于结构约束,类型T必须是值类型
where T:class-->类约束,类型T必须是引用类型
where T:IBase-->接口约束,类型T必须实现接口IBase
where T:BaseClass-->类继承约束,类型T必须派生自基类BaseClass
where T:new()-->构造函数约束,类型T必须有一个公共的无参数的构造函数
where T1:T2-->类型T1不行派生自类型T2

E.G

public class DocumentManager<T> where T: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 DisplayAllDocument()
{
foreach (T doc in documentQueue)
{
string title = 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)
{
Title = title;
Content = content;
}
public string Title { get; set; }
public string Content { get; set; }
}
3、泛型接口
public interface IComparable<in T>
{
int CompareTo(T other)
}


4、泛型结构
5、泛型方法


void Swap<T>(ref T x,ref T y)
{
T Temp;
Temp=x;
x=y;
y=Temp;
}
//调用
int i=9,j=8;
Swap<int>(i,j);


6、泛型委托


public delegate void mydelegate<in sdele>(sdele obj);

原文地址:https://www.cnblogs.com/mingjia/p/4462988.html