C#泛型的使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/*
* 1、泛型结构
* 2、泛型委托
* 3、泛型方法
*/
namespace ExGenericStruct
{
//泛型结构
struct PiceOfData<T>
{
public PiceOfData(T _value)
{
_Data = _value;
}
private T _Data;
public T Data
{
get { return _Data; }
set { _Data = value; }
}
}
//泛型委托
public delegate TR Func<T1,T2,TR>(T1 p1,T2 p2);
class simple
{
static public string PrintString(int p1, int p2)
{
int total = p1 + p2;
return total.ToString();
}
public static void ReverseAndPrint<T>(T[]arr)
{
Array.Reverse(arr);
foreach (T item in arr)
{
Console.Write("{0}\t\t",item.ToString());
}
Console.WriteLine();
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("泛型结构");
var intData = new PiceOfData<int>(30);
var stringData = new PiceOfData<string>("Hi There");
Console.WriteLine("intData:{0}", intData.Data);
Console.WriteLine("stringData:{0}", stringData.Data);
Console.WriteLine("泛型委托");
var myDel = new Func<int, int, string>(simple.PrintString);
Console.WriteLine("Total:{0}",myDel(13,14));
Console.WriteLine("泛型方法");
var intArray = new int[] { 1, 2, 3 };
var stringArray = new string [] { "asd","dff","dsfe" };
var doubleArray = new double[] { 1.234, 2.345, 3.456 };
simple.ReverseAndPrint<int>(intArray);//调用方法
simple.ReverseAndPrint(intArray);//引用类型并调用,让编译器推断类型
simple.ReverseAndPrint<string>(stringArray);//调用方法
simple.ReverseAndPrint(stringArray);//引用类型并调用
simple.ReverseAndPrint<double>(doubleArray);//调用方法
simple.ReverseAndPrint(doubleArray);//引用类型并调用
Console.ReadLine();
}
}
}