class Program
{
static void Main(string[] args)
{
Func<int, int, int> add = Add;
Action<string> print = Print;
print(add(1, 2).ToString());
Console.ReadKey();
}
static int Add(int i, int j)
{
return i + j;
}
static void Print(string msg)
{
Console.WriteLine(msg);
}
}
从以上的方法中注意到:Add方法和Print方法只有一条语句,因此使用匿名方法改写。
static void Main(string[] args)
{
Func<int,int ,int> add=new Func<int, int, int >(delegate(int i,int j)
{ return i + j; });
Action<string> print = new Action<string>(delegate (string msg)
{ Console.WriteLine(msg); });
print(add(1, 2).ToString());
Console.ReadKey();
}
Lambda表达式实现:
static void Main(string[] args)
{
Func<int, int, int> add = (i, j) => { return i + j; };
Action<string> print = (msg) =>
{ Console.WriteLine(msg); };
print(add(1, 2).ToString());
Console.ReadKey();
}