首页 > 开发 > 综合 > 正文

C#中多重委托(MulticastDelegate)的例子

2024-07-21 02:26:34
字体:
来源:转载
供稿:网友


using system;

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;
  }
 }
}
 

 

 



发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表