close
C# 中的委派 (Delegation)
委派
using System;
// Declare delegate -- defines required signature:
delegate void SampleDelegate(string message);
class MainClass
{
// Regular method that matches signature:
static void SampleDelegateMethod(string message)
{
Console.WriteLine(message);
}
static void Main()
{
// Instantiate delegate with named method:
SampleDelegate d1 = SampleDelegateMethod;
// Instantiate delegate with anonymous method:
SampleDelegate d2 = delegate(string message)
{
Console.WriteLine(message);
};
// Invoke delegate d1:
d1("Hello");
// Invoke delegate d2:
d2(" World");
}
}
事件
C#物件 事件 委派 撰寫 範例
using System;
using System.Collections.Generic;
using System.Text;
namespace eventSimple
{
class Program
{
delegate void myFunction(string text);
static event myFunction readKeyEvent;
static void Main(string[] args)
{
readKeyEvent += new myFunction(myFunction1);
Console.WriteLine("請輸入一字串");
string text = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("第一次觸發事件");
readKeyEvent.Invoke(text);
Console.WriteLine();
readKeyEvent += new myFunction(myFunction2);
Console.WriteLine("請輸入一字串");
text = Console.ReadLine();
Console.WriteLine();
Console.WriteLine("第二次觸發事件");
readKeyEvent.Invoke(text);
Console.WriteLine();
Console.WriteLine("按任意鍵離開");
Console.ReadKey();
}
static void myFunction1(string text)
{
Console.WriteLine("這次第一次執行的函數");
Console.WriteLine("參數="+text);
}
static void myFunction2(string text)
{
Console.WriteLine("這次第二次執行的函數");
Console.WriteLine("參數=" + text);
}
}
}
參考文獻
陳鍾誠 (2010年06月10日),(網頁標題) C# 中的委派 (Delegation),(網站標題) 免費電子書:C# 程式設計,2010年06月10日,取自 http://cs0.wikidot.com/delegation ,網頁修改第 0 版。
文章標籤
全站熱搜