泛型委托
原来实现对int数组排序、对string数组排序,要用到两个委托和两个方法;
如果用泛型委托的话只需要一个委托和一个方法,通过泛型T的值决定是对int还是对string排序,委托类型参数值可以是现有方法也可以是匿名方法。
泛型方法对T赋予具体类型后,其中的泛型委托参数就跟普通委托一样了。
DelegateHelper.cs文件如下:
public delegate int SortGenericEventHandler<T>(T max,T other);
public delegate int SortIntEventHandler(int max, int other);
public delegate int SortStringEventHandler(string max, string other);
class DelegateHelper
{
//只能对int数组排序
public void Sort(int[] array, SortIntEventHandler sort)
{
int temp = 0;
for (int i = 0; i < array.Length - 1; i++)
{
for (int j = 0; j < array.Length - 1 - i; j++)
{
if (sort(array[j], array[j + 1]) > 0)
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
//只能对string数组排序
public void Sort(string[] array, SortStringEventHandler sort)
{
string temp = string.Empty;
for (int i = 0; i < array.Length - 1; i++)
{
for (int j = 0; j < array.Length - 1 - i; j++)
{
if (sort(array[j], array[j + 1]) > 0)
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
//通过泛型方法与泛型委托,既能对string数组排序又能对int数组排序
public void SortGeneric<T>(T[] array, SortGenericEventHandler<T> sort)
{
T temp ;
for (int i = 0; i < array.Length - 1; i++)
{
for (int j = 0; j < array.Length - 1 - i; j++)
{
if (sort(array[j], array[j + 1]) > 0)
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
public int SortInt(int max, int other)
{
return max - other;
}
public int SortString(string max, string other)
{
return max.Length - other.Length;
}
}
Program.cs文件代码如下:
static void Main(string[] args)
{
//非泛型写法
int[] intArray= new int[] { 3, 9, 8, 6, 7, 2, 1 };
new DelegateHelper().Sort(intArray, new DelegateHelper().SortInt);
for (int i = 0; i < intArray.Length; i++)
{
Console.WriteLine("intArray[{0}]={1}", i, intArray[i]);
}
Console.WriteLine("------------------");
string[] strArray = new string[] { "acdefg", "asc", "a", "aegrs", "da" };
new DelegateHelper().Sort(strArray, new DelegateHelper().SortString);
for (int i = 0; i < strArray.Length; i++)
{
Console.WriteLine("strArray[{0}]={1}", i, strArray[i]);
}
}
static void Main(string[] args)
{
//泛型委托写法
int[] intArray= new int[] { 3, 9, 8, 6, 7, 2, 1 };
string[] strArray = new string[] { "acdefg", "asc", "a", "aegrs", "da" };
//【方法一】传递现存方法
new DelegateHelper().SortGeneric<int>(intArray,new DelegateHelper().SortInt);
//【方法二】传递匿名方法
new DelegateHelper().SortGeneric<int>(intArray, delegate(int max, int other)
{
return max - other;
});
for (int i = 0; i < intArray.Length; i++)
{
Console.WriteLine("intArray[{0}]={1}", i, intArray[i]);
}
Console.WriteLine("------------------");
//【方法一】传递现存方法
new DelegateHelper().SortGeneric<string>(strArray, new DelegateHelper().SortString);
//【方法二】传递匿名方法
new DelegateHelper().SortGeneric<string>(strArray, delegate(string max, string other)
{
return max.Length - other.Length;
});
for (int i = 0; i < strArray.Length; i++)
{
Console.WriteLine("strArray[{0}]={1}", i, strArray[i]);
}
Console.ReadKey();
}
非泛型写法与泛型写法运行结果相同,运行结果如下: