using System; namespace SEI.DL88250.SourceCodes.CSharp public void Add(decimal add1, decimal add2, ref decimal result) public void Sub(decimal sub1, decimal sub2, ref decimal result) public void Mul(decimal mul1, decimal mul2, ref decimal result) static void Main(string[] args) mcd.MyAdd = new Calculation(mcd.Add); Console.ForegroundColor = ConsoleColor.DarkRed; Console.ForegroundColor = ConsoleColor.DarkRed; Console.ForegroundColor = ConsoleColor.DarkRed; // restore Delegate Sub method Console.ForegroundColor = ConsoleColor.DarkRed;
{
public delegate void Calculation(decimal val1,
decimal val2,
ref decimal result);
class MulticastDelegate
{
Calculation MyAdd;
Calculation MySub;
Calculation MyMul;
{
result = add1 + add2;
Console.WriteLine("{0} + {1} = {2}",
add1, add2, result);
}
{
result = sub1 - sub2;
Console.WriteLine("{0} - {1} = {2}",
sub1, sub2, result);
}
{
result = mul1 * mul2;
Console.WriteLine("{0} * {1} = {2}",
mul1, mul2, result);
}
{
decimal result = 0.0m;
MulticastDelegate mcd = new MulticastDelegate();
mcd.MySub = new Calculation(mcd.Sub);
mcd.MyMul = new Calculation(mcd.Mul);
Console.WriteLine("Use Single Delegate: ");
Console.ForegroundColor = ConsoleColor.DarkGray;
mcd.MyAdd(7.43m, 5.19m, ref result);
mcd.MySub(7.43m, 5.19m, ref result);
mcd.MyMul(7.43m, 5.19m, ref result);
Console.WriteLine("Use Multicast Delegate: ");
Console.ForegroundColor = ConsoleColor.DarkGray;
Calculation MultiCalc = mcd.MyAdd + mcd.MySub + mcd.MyMul;
MultiCalc(7.43m, 5.19m, ref result);
Console.WriteLine("Remove the Sub method Delegate: ");
Console.ForegroundColor = ConsoleColor.DarkGray;
MultiCalc -= mcd.MySub;
MultiCalc(7.43m, 5.19m, ref result);
MultiCalc += mcd.MySub;
Console.WriteLine("Delegate contents: ");
Console.ForegroundColor = ConsoleColor.DarkGray;
Delegate[] delegateArray = MultiCalc.GetInvocationList();
foreach (Delegate delgt in delegateArray)
{
Console.WriteLine(delgt.Method.GetBaseDefinition());
}
Console.ForegroundColor = ConsoleColor.White;
}
}
}
C#中多重委托(MulticastDelegate)的例子
80酷酷网 80kuku.com