T:struct //类型必须是值类型 T:class //类型必须是引用类型 T:baseClassName //类型必须是baseClass或者是baseClass的派生类 T:interfaceName //类型参数必须是指定的接口或实现指定的接口。 可以指定多个接口约束。 约束接口也可以是泛型的 T:new() //类型必须有一个无参数的public构造函数,多约束存在时,new必须放在最后 T:U //类型T必须是类型U的同类型或者是U的派生类
class BaseNode { } class BaseNodeGeneric<T> { } // concrete type class NodeConcrete<T> : BaseNode { } //closed constructed type class NodeClosed<T> : BaseNodeGeneric<int> { } //open constructed type class NodeOpen<T> : BaseNodeGeneric<T> { }
class BaseNodeMultiple<T, U> { } class Node4<T> : BaseNodeMultiple<T, int> {} //No error class Node5<T, U> : BaseNodeMultiple<T, U> {} //No error //class Node6<T> : BaseNodeMultiple<T, U> {} //Generates an error
class NodeItem<T> where T : System.IComparable<T>, new() { } class SpecialNodeItem<T> : NodeItem<T> where T : System.IComparable<T>, new() { } <5>Open constructed and closed constructed types可以用作函数的参数 void Swap<T>(List<T> list1, List<T> list2) { //code to swap items } void Swap(List<int> list1, List<int> list2) { //code to swap items }
class GenericList<T> { // CS0693 void SampleMethod<T>() { } } class GenericList2<T> { //No warning void SampleMethod<U>() { } }
//下面这个方法现在只能被实现了System.IComparable<T>的参数T使用。 void SwapIfGreater<T>(ref T lhs, ref T rhs) where T : System.IComparable<T> { T temp; if (lhs.CompareTo(rhs) > 0) { temp = lhs; lhs = rhs; rhs = temp; } }
class SampleClass<T> { void Swap(ref T lhs, ref T rhs) { } }
class Program { static void Main(string[] args) { int[] arr = new int[] { 1,2,35,4,78}; process<int>(arr); } private static void process<T>(IList<T> cell) { foreach (T i in cell) { Console.WriteLine("This is "+i); } } }
public delegate void Del<T>(T item); public static void Notify(int i) { } Del<int> m1 = new Del<int>(Notify); // this is ok too Del<int> m2 = Notify;
class Stack<T> { T[] items; int index; public delegate void StackDelegate(T[] items); }
private static void DoWork(float[] items) { } public static void TestStack() { Stack<float> s = new Stack<float>(); Stack<float>.StackDelegate d = DoWork;//委托可以通过类名来调用 }
原文:http://blog.csdn.net/ddupd/article/details/22416299