+,+=,--,-=等运算符就不说了。
1.组合委托Combine静态方法
public static Delegate Combine(Delegate[])
public static Delegate Combine(Delegate,Delegate)
不同的继承,注意显式转换。
2.Remove方法
public static Delegate Remove(Delegate source,Delegate value)
注意:Combine抑或Remove都会返回一个新构造的委托对象【委托链】,Remove后调用委托时注意检查null。
3.GetInvocationList方法
public static Delegate[] GetInvocationList();
返回组合委托的(单播)委托数组列表。
代码示例
using System;
using System.Collections.Generic;
using System.Text;
namespace numbers
{
delegate void MathOperation(int var1,int var2);
class Program
{
public static void plus(int var1, int var2)
{
Console.WriteLine("{0} + {1} = {2}",var1,var2,var1 + var2);
}
public static void minus(int var1, int var2)
{
Console.WriteLine("{0} - {1} = {2}", var1, var2, var1 - var2);
}
public static void multiply(int var1, int var2)
{
Console.WriteLine("{0} * {1} = {2}", var1, var2, var1 * var2);
}
public static void divide(int var1, int var2)
{
Console.WriteLine("{0} / {1} = {2}", var1, var2, var1 / var2);
}
public static void Main(string[] args)
{
//代理人x
MathOperation x1 = new MathOperation(plus) + new MathOperation(minus);
MathOperation x2 = new MathOperation(multiply) + new MathOperation(divide);
x2 = (MathOperation)Delegate.Combine(x1,x2);
x2(3, 2);
x2 = (MathOperation)Delegate.Remove(x2, x1);
x2(3, 2);
x2 = (MathOperation)x2.GetInvocationList()[0];
x2(3, 2);
}
}
}
using System.Collections.Generic;
using System.Text;
namespace numbers
{
delegate void MathOperation(int var1,int var2);
class Program
{
public static void plus(int var1, int var2)
{
Console.WriteLine("{0} + {1} = {2}",var1,var2,var1 + var2);
}
public static void minus(int var1, int var2)
{
Console.WriteLine("{0} - {1} = {2}", var1, var2, var1 - var2);
}
public static void multiply(int var1, int var2)
{
Console.WriteLine("{0} * {1} = {2}", var1, var2, var1 * var2);
}
public static void divide(int var1, int var2)
{
Console.WriteLine("{0} / {1} = {2}", var1, var2, var1 / var2);
}
public static void Main(string[] args)
{
//代理人x
MathOperation x1 = new MathOperation(plus) + new MathOperation(minus);
MathOperation x2 = new MathOperation(multiply) + new MathOperation(divide);
x2 = (MathOperation)Delegate.Combine(x1,x2);
x2(3, 2);
x2 = (MathOperation)Delegate.Remove(x2, x1);
x2(3, 2);
x2 = (MathOperation)x2.GetInvocationList()[0];
x2(3, 2);
}
}
}