标签:
using System; using System.Collections; using System.Collections.Generic; using System.IO; namespace codeTest { class Program { //委托泛型的使用 delegate T ShowNum<T>(T n); static int Show(int num) { return num; } static void Main(string[] args) { //MyGeneric<int,int> myGenericInt = new MyGeneric<int,int>(5); //SubClass myGenericInt = new SubClass(5); SubClass2<int, int> myGenericInt = new SubClass2<int, int>(5); for (int i = 0; i < myGenericInt.arry.Length; i++) { myGenericInt.SetArryValue(i, i); } for (int i = 0; i < myGenericInt.arry.Length; i++) { Console.WriteLine(myGenericInt.GetArryValue(i)); } string a = "11", b = "22"; Console.WriteLine("a is {0},b is {1}", a, b); swap<string>(ref a, ref b); Console.WriteLine("a is {0},b is {1}",a,b); ShowNum<int> dele = new ShowNum<int>(Show); Console.WriteLine(string.Format("Show num is {0}", dele(10))); Console.ReadLine(); } //在方法上实现泛型 static void swap<T>(ref T a, ref T b) where T : class { T tmp; tmp = a; a = b; b = tmp; } } //在类上实现泛型 class MyGeneric<T, K> where T : struct { //where T:class 引用类型 //where T:struct 值类型 //where T:interface 接口 //where T:具体的基类 public T[] arry; public MyGeneric(int index) { arry = new T[index]; } public T GetArryValue(int index) { return arry[index]; } public void SetArryValue(int index, T value) { arry[index] = value; } } //继承泛型时指定类型后,基类不再是泛型 class SubClass : MyGeneric<int, int> { public SubClass(int num) : base(num) { } } class SubClass2<T, K> : MyGeneric<T, K> where T : struct { public SubClass2(int num) : base(num) { } } }
标签:
原文地址:http://www.cnblogs.com/lgxlsm/p/4772108.html