声明泛型类
与声明普通类差不多,区别如下。
在类名之后放置一组尖括号。
在尖括号中用逗号分隔的占位符字符串来表示希望提供的类型。这叫做类型参数
在泛型类声明的主体中使用类型参数来表示应该替代的类型。
class SomeClass<T1, T2>
{
public T1 SomeVar = new T1();
public T2 OtherVar = new T2();
}
要让泛型变的更有用,我们需要提供额外的信息让编译器知道参数可以接受哪些类型。
这些额外的类型叫做约束。
只有符合约束条件的类型才能替代所给的类型参数,来产生构造类型。
泛型方法
static public void ReverseAndPrint<T>(T[] arr)
{
Array.Reverse(arr);
foreach (T item in arr)
Console.Write("{0},",item.ToString());
Console.WriteLine("");
}
}
class Program
{
static void Main(string[] args)
{
//创建各种类型的数组
var intArray = new int[] { 3,5,7,9,11};
var stringArray = new string[] { "first","second","third"};
var doubleArray = new double[] { 3.567, 7.893, 2.431 };
Simple .ReverseAndPrint<int>(intArray);//调用方法
Simple.ReverseAndPrint(intArray);//推断类型并调用
Simple.ReverseAndPrint<string>(stringArray);//调用方法
Simple.ReverseAndPrint(stringArray);//推断类型并调用
Simple.ReverseAndPrint<double>(doubleArray);//调用方法
Simple.ReverseAndPrint(doubleArray);//推断类型并调用
}
泛型结构
struct PieceOfData<T>//泛型结构
{
private T _data;
public PieceOfData(T value) { _data = value; }
public T Data
{
get { return _data; }
set { _data = value; }
}
}
class Program
{
static void Main(string[] args)
{
var intData = new PieceOfData<int>(10);
var stringData = new PieceOfData<string>("hi");
Console.WriteLine("intData={0}",intData.Data);
Console.WriteLine("stringData={0}", stringData.Data);
}
泛型委托
delegate void MyDelegata<T>(T value);//泛型委托
class Simple
{
static public void PrintString(string s)//方法匹配委托
{
Console.WriteLine(s);
}
static public void PrintUpperString(string s)//方法匹配委托
{
Console.WriteLine("{0}",s.ToUpper());
}
}
class Program
{
static void Main(string[] args)
{
var myDel =
new MyDelegata<string>(Simple.PrintString);
myDel += Simple.PrintUpperString;
myDel("Hi There");
}
泛型接口
interface IMyIfc<T>//泛型接口
{
T ReturnIt(T inValue);
}
class Simple<S> : IMyIfc<S>//泛型类
{
public S ReturnIt(S inValue)//实现泛型接口
{
{return inValue;}
}
}
class Program
{
static void Main(string[] args)
{
var trivInt = new Simple<int>();
var trivString=new Simple<string>();
Console.WriteLine("{0}",trivInt.ReturnIt(5));
Console.WriteLine("{0}",trivString.ReturnIt("Hi there"));
}