using
System;
namespace
泛型委托
{
public
delegate
int
DelMax<T>(T max,T temp);
/// <summary>
/// 通用取最大值
/// </summary>
class
Program
{
static
void
Main(
string
[] args)
{
string
[] str = {
"a"
,
"bb"
,
"ccc"
,
"dddd"
};
int
[] nums = {1, 2, 3, 4, 5, 6};
Console.WriteLine(
"1.0进行整数型比较"
);
/* 整数比较大小 */
//第一种 匿名函数
int
num = GetMax<
int
>(nums,
delegate
(
int
max,
int
temp) {
return
max - temp; });
Console.WriteLine(
"匿名函数:"
+ num);
//第二种 lambda 表达式
num=GetMax<
int
>(nums, (
int
max,
int
temp)=> max - temp);
Console.WriteLine(
"lambda:"
+ num);
Console.WriteLine(
"2.0进行文本数型比较"
);
/* 文本比较大小 */
//第一种 匿名函数
string
strRt = GetMax<
string
>(str,
delegate
(
string
max,
string
temp) {
return
max.Length - temp.Length; });
Console.WriteLine(
"匿名函数:"
+ strRt);
//第二种 lambda 表达式
strRt = GetMax<
string
>(str, (
string
max,
string
temp) => max.Length - temp.Length);
Console.WriteLine(
"lambda:"
+ strRt);
Console.ReadKey();
}
/// <summary>
/// 通过泛型进行比较
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tempObjects"></param>
/// <param name="delMax"></param>
/// <returns></returns>
public
static
T GetMax<T>(T[] tempObjects, DelMax<T> delMax)
{
T max = tempObjects[0];
for
(
int
i = 0; i < tempObjects.Length; i++)
{
if
(delMax(max, tempObjects[i]) < 0)
{
max = tempObjects[i];
}
}
return
max;
}
}
}