using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DelegateMethod
{
internal delegate void DelegateVoidHandler(string a);
internal delegate int DelegateFunctionHandler(int a);
class Program
{
static void Main(string[] args)
{
int res = 0;
//以下两种效果相同
res = TestAction(1, 3, voidMethod);
Console.WriteLine("指定实体方法传入:" + res.ToString());
res = TestAction(1, 3, i=>{i.ToString();});
Console.WriteLine("指定匿名方法传入:" + res.ToString());
//以下五种效果相同
//Func<int, int> fun 效果等同于 delegate int DelegateFunctionHandler(int a)
res = TestDelegate(2, 3, (val) =>
{ return val * val; }
);
Console.WriteLine("指定匿名函数传入:" + res.ToString());
res = TestDelegate(3, 3, delegate(int a) { return a * a; });
Console.WriteLine(res.ToString());
res = TestDelegate(4, 3, functionMethod);
Console.WriteLine(res.ToString());
res = TestFunc(5, 3, (a) =>
{ return a * a; }
);
Console.WriteLine("指定匿名函数传入:" + res.ToString());
res = TestFunc(6, 3, delegate(int a)
{ return a * a; }
);
Console.WriteLine("指定匿名函数传入:" + res.ToString());
Console.ReadKey();
}
/// <summary>
/// 封装方法参数的方法
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="action"></param>
/// <returns></returns>
private static int TestAction(int a, int b, Action<int> action)
{
int sum = a + b;
if (action == null) return sum;
action(sum);
return sum;
}
/// <summary>
/// 带委托函数的方法
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="action">委托参数,可以传入匿名函数和实体函数</param>
/// <returns></returns>
private static int TestDelegate(int a, int b, DelegateFunctionHandler action)
{
int sum = a + b;
if (action == null) return sum;
sum = action(sum);
return sum;
}
private static int TestFunc(int a, int b, Func<int, int> fun)
{
int sum = a + b;
if (fun == null) return sum;
sum = fun(sum);
return sum;
}
public static void voidMethod(int a)
{
a = a + 1;
}
private static int functionMethod(int a)
{
return a * a;
}
}
}