namespace SEI.DL88250.SourceCodes.CSharp
{
public delegate void Calculation(decimal val1,
decimal val2,
ref decimal result);
class MulticastDelegate
{
Calculation MyAdd;
Calculation MySub;
Calculation MyMul;
public void Add(decimal add1, decimal add2, ref decimal result)
{
result = add1 + add2;
Console.WriteLine("{0} + {1} = {2}",
add1, add2, result);
}
public void Sub(decimal sub1, decimal sub2, ref decimal result)
{
result = sub1 - sub2;
Console.WriteLine("{0} - {1} = {2}",
sub1, sub2, result);
}
public void Mul(decimal mul1, decimal mul2, ref decimal result)
{
result = mul1 * mul2;
Console.WriteLine("{0} * {1} = {2}",
mul1, mul2, result);
}
static void Main(string[] args)
{
decimal result = 0.0m;
MulticastDelegate mcd = new MulticastDelegate();
mcd.MyAdd = new Calculation(mcd.Add);
mcd.MySub = new Calculation(mcd.Sub);
mcd.MyMul = new Calculation(mcd.Mul);
Console.ForegroundColor = ConsoleColor.DarkRed;
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.ForegroundColor = ConsoleColor.DarkRed;
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.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("Remove the Sub method Delegate: ");
Console.ForegroundColor = ConsoleColor.DarkGray;
MultiCalc -= mcd.MySub;
MultiCalc(7.43m, 5.19m, ref result);
// restore Delegate Sub method
MultiCalc += mcd.MySub;
Console.ForegroundColor = ConsoleColor.DarkRed;
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;
}
}
}