程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C#中多重委托(MulticastDelegate)的例子

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

編輯:關於C語言
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;
  }
 }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved