c# 委託的定義及使用例項
阿新 • • 發佈:2019-01-29
namespace 委託測試
{
//小明類
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//宣告一個委託,其實就是個“命令”
public delegate void BugTicketEventHandler();
public delegate void BugTicketEventHandler2(object obj);
private void button1_Click(object sender, EventArgs e)
{
//不帶引數委託呼叫
//這裡就是具體闡述這個命令是幹什麼的,本例是MrZhang.BuyTicket“小張買車票”
BugTicketEventHandler myDelegate = new BugTicketEventHandler(MrZhang.BuyTicket);
myDelegate += MrZhang.BuyMovieTicket;
//這時候委託被附上了具體的方法
myDelegate();
//帶引數的靜態委託呼叫
BugTicketEventHandler2 myDelegate2 = new BugTicketEventHandler2(MrZhang.BuyDoorTicket);
myDelegate2("帶引數委拖");
//帶引數的非靜態委託呼叫
MrZhang MZ = new MrZhang();
BugTicketEventHandler2 myDelegate3 = new BugTicketEventHandler2(MZ.BuyDoor);
myDelegate3("非靜態帶引數委拖");
}
}
//小張類
public class MrZhang
{
//其實買車票的悲情人物是小張
public static void BuyTicket()
{
MessageBox.Show("NND,每次都讓我去買票,雞人呀!");
}
public static void BuyMovieTicket()
{
MessageBox.Show("我去,自己泡妞,還要讓我帶電影票!");
}
public static void BuyDoorTicket(object obj)
{
string str = obj as string;
MessageBox.Show(str);
}
public void BuyDoor(object obj)
{
string str = obj as string;
MessageBox.Show(str);
}
}
}
{
//小明類
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//宣告一個委託,其實就是個“命令”
public delegate void BugTicketEventHandler();
public delegate void BugTicketEventHandler2(object obj);
private void button1_Click(object sender, EventArgs e)
{
//不帶引數委託呼叫
//這裡就是具體闡述這個命令是幹什麼的,本例是MrZhang.BuyTicket“小張買車票”
BugTicketEventHandler myDelegate = new BugTicketEventHandler(MrZhang.BuyTicket);
myDelegate += MrZhang.BuyMovieTicket;
//這時候委託被附上了具體的方法
myDelegate();
//帶引數的靜態委託呼叫
BugTicketEventHandler2 myDelegate2 = new BugTicketEventHandler2(MrZhang.BuyDoorTicket);
myDelegate2("帶引數委拖");
//帶引數的非靜態委託呼叫
MrZhang MZ = new MrZhang();
BugTicketEventHandler2 myDelegate3 = new BugTicketEventHandler2(MZ.BuyDoor);
myDelegate3("非靜態帶引數委拖");
}
}
//小張類
public class MrZhang
{
//其實買車票的悲情人物是小張
public static void BuyTicket()
{
MessageBox.Show("NND,每次都讓我去買票,雞人呀!");
}
public static void BuyMovieTicket()
{
MessageBox.Show("我去,自己泡妞,還要讓我帶電影票!");
}
public static void BuyDoorTicket(object obj)
{
string str = obj as string;
MessageBox.Show(str);
}
public void BuyDoor(object obj)
{
string str = obj as string;
MessageBox.Show(str);
}
}
}