得到委托列表:
Delegate[] deleteArray = actDelete.GetInvocationList();
foreach(Delegate item in deleteArray)
{
item.DynamicInvoke();
}
清空委托列表:
Delegate[] deleteArray = actDelete.GetInvocationList();
for (int i = 0; i < deleteArray.Length;i++)
{
actDelete -= deleteArray[i] as Action
}
源代码:
/***
*委托的取值与清空
*
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 取得与清空委托列表
{
class Program
{
Action actHandler = null;
public Program()
{
actHandler += DeleteMethod1;
actHandler += DeleteMethod2;
actHandler += DeleteMethod3;
}
public void DeleteMethod1()
{
Console.WriteLine("DeleteMethod1");
}
public void DeleteMethod2()
{
Console.WriteLine("DeleteMethod2");
}
public void DeleteMethod3()
{
Console.WriteLine("DeleteMethod3");
}
/// <summary>
/// 测试1,取得委托列表
/// </summary>
public void Test1()
{
Console.WriteLine("取得委托列表");
Delegate[] delArray = actHandler.GetInvocationList();
foreach (var item in delArray)
{
item.DynamicInvoke();
}
}
/// <summary>
/// 清空委托列表
/// </summary>
public void Test2()
{
while (actHandler != null)
{
actHandler -= this.actHandler;
}
//验证
if (actHandler != null)
{
actHandler.Invoke();
}
else
{
Console.WriteLine("委托现在已经清空了");
}
}
/// <summary>
/// 清空委托列表更强大的算法
/// </summary>
public void Test3()
{
Delegate[] delArray = actHandler.GetInvocationList();
for (int i = 0; i < delArray.Length; i++)
{
actHandler -= delArray[i] as Action;
}
//测试
if (actHandler != null)
{
actHandler.Invoke();
}
else
{
Console.WriteLine("委托现在已经清空了");
}
}
static void Main(string[] args)
{
Program obj = new Program();
//obj.Test1();
//obj.Test2();
obj.Test3();
}
}
}