委托的清空
(1).在类中申明清空委托方法,依次循环去除委托引用。
方法如下:
public MethodDelegate OnDelegate;
public void ClearDelegate()
{
while (this.OnDelegate != null)
{
this.OnDelegate -= this.OnDelegate;
}
}
(2).如果在类中没有申明清空委托的方法,我们可以利用GetInvocationList查询出委托引用,然后进行去除。
方法如下:
public MethodDelegate OnDelegate;
static void Main(string[] args)
{
Program test = new Program();
if (test.OnDelegate != null)
{
System.Delegate[] dels = test.OnDelegate.GetInvocationList();
for (int i = 0; i < dels.Length; i++)
{
test.OnDelegate -= dels[i] as MethodDelegate;
}
}
}