1.委托
在.NET中,委托使用得非常频繁,委托是方法的指针。委托可以通过指向不同的方法来实现灵活调用。委托的使用方式如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DelegateAnonymousMethodLamdaExpression
{
delegate int ChangeValue(int input);
class Program
{
static ChangeValue changeValue1;
static ChangeValue changeValue2;
static void Main(string[] args)
{
changeValue1 = Change1;
Console.WriteLine(changeValue1(10));
changeValue1 = Change2;
Console.WriteLine(changeValue1(10));
changeValue2 += Change3;
changeValue2 += Change4;
changeValue2(20);
Console.ReadKey();
}
static int Change1(int x)
{
return x + 5;
}
static int Change2(int x)
{
return x + 10;
}
static int Change3(int x)
{
Console.WriteLine (x + 5);
return x + 5;
}
static int Change4(int x)
{
Console.WriteLine(x + 10);
return x + 10;
}
}
}
输出结果:
2.匿名方法
匿名方法是使用delegate关键字来使用的,下面的例子就是使用匿名方法的例子。
ChangeValue cv = delegate(int x) { return x * 5; };
Console.WriteLine(cv(50));
匿名方法使用有一定的局限性,就是逻辑不宜过长。
3.LAMDA 表达式
LAMDA表达式非常简洁,能够作为匿名方法的替代。
ChangeValue myDel = x => x * 5;
Console.WriteLine(myDel(50));
这就是委托,匿名方法和LAMDA表达式的使用。
源代码下载:http://download.csdn.net/detail/afandaafandaafanda/8320033