delegate void MyDelegate();
MyDelegate a=()=>Console.WriteLine(1);
MyDelegate a+=()=>Console.WriteLine(2);
我在委托里注册了两个lambda表达式 我怎样才能只移除第一个lambda表达式
我用a-=()=>Console.WriteLine(1);后调用a()还是输出1 2.
求解答
只能通过反射的方式删除已经添加到委托链中的方法。
这样的需求其实不应该推荐lambda表达式,一般的方法就能移除
每次Lamda表达式都会生成一个匿名的方法,每次生成的匿名的方法当然不一样了。
你试着删除的那个匿名方法,并不是和第1次加入的匿名方法是一样的东东。
但如果按照如下这样,就是可以删除的。
private delegate void MyDelegate();
static void Main(string[] args)
{
MyDelegate a = MethodA;
MyDelegate b = MethodB;
MyDelegate ab = a + b;
Console.WriteLine("====> Calling MyDelegate ab...");
ab();
ab -= MethodA;
Console.WriteLine("====> Calling MyDelegate c...");
ab();
}
private static void MethodA()
{
Console.WriteLine("Method A");
}
private static void MethodB()
{
Console.WriteLine("Method B");
}
=======================
====> Calling MyDelegate ab...
Method A
Method B
====> Calling MyDelegate c...
Method B
Press any key to continue . . .
当然也可以按照下面的方法
private delegate void MyDelegate();
static void Main(string[] args)
{
MyDelegate a = ()=>Console.WriteLine("A");
MyDelegate b = ()=>Console.WriteLine("B");
MyDelegate ab = a + b;
Console.WriteLine("====> Calling ab...");
ab();
** ab = (MyDelegate)Delegate.Remove(ab, ab.GetInvocationList()[0]);**
Console.WriteLine("====> Calling ab...");
ab();
}
====================
====> Calling ab...
A
B
====> Calling ab...
B
Press any key to continue . . .