在使用Delegate的时候,很多时候对于有些方法我们只可能使用一次,所以不必去写一个普通方法,这时我们就可以使用匿名方法来解决
匿名方法就是没有名字的方法。定义语法:MyDelegate p = delegate(int s){s=10;};
我们用如下代码进行测试,然后使用VS设置断点来看看具体的执行过程
class Program
{
static void Main(string[] args)
{
MyDelegate md = delegate (int s) { return s; } ;
Console.WriteLine(md(2));
Console.ReadKey();
}
}
delegate int MyDelegate(int s);
最后按F11的发现又会去执行到delegate后面的代码,这个就是我们写的匿名方法了
方法执行完以后,再继续去执行下面的代码,最后控制带输出2
其实我们所谓的匿名方法只是在代码上来说的,在真正的IL代码来说,其实是名字的,我们使用反编译工具来查看一下
我们可以改造下之前写的那个例子
delegate bool CompareNum(object obj1, object obj2);
class Program
{
static void Main(string[] args)
{
object[] nums = { 1, 2, 23, 321, 124, 24321, 214 };
Func<object, object, bool> cpn = delegate (object obj1, object obj2)
{
int i1 = (int)obj1;
int i2 = (int)obj2;
return i1 > i2;
};
int max = (int)GetMax(nums, cpn);
Console.WriteLine(max);
Console.ReadKey();
}
static object GetMax(object[] obj, Func<object, object, bool> cpn)
{
object max = obj[0];
for (int i = 1; i < obj.Length; i++)
{
if (!cpn(max, obj[i]))
{
max = obj[i];
}
}
return max;
}
}
然后运行结果和之前的一模一样,但是有人会说,你这样不是和之前的比就是没有取名字,有什么用呢?
现在看来这个确实没有什么用,但是当和Lambda表达式结合起来使用的话,就会发现他的强大!lambda表达式后面也会写的!!!
---本博客是学习以后记录知识,如有侵权,请联系删除!!!