c#委托學(xué)習(xí)示例分享
1.委托
總的來說,委托是一個(gè)類,它定義了方法的類型,使得可以將方法當(dāng)作另一個(gè)方法的參數(shù)來進(jìn)行傳遞,這種將方法動(dòng)態(tài)地賦給參數(shù)的做法,可以避免在程序中大量使用If-Else(Switch)語句,同時(shí)使得程序具有更好的可擴(kuò)展性。所以,引入委托后,編程人員可以把方法的引用封裝在委托對象中,然后把委托對象傳遞給需要引用方法。調(diào)用委托和調(diào)用方法的方式是一模一樣的,代碼如下:
a.代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WForms
{
public partial class Form1 : Form
{
//定義委托
private delegate void WriteTextBox(char ch);
//聲明委托
private WriteTextBox writeTextBox;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (checkBox1.Checked == true)
{
textBox1.Clear();
textBox1.Refresh();
// 實(shí)例化委托- 方法WriteTextBox1
writeTextBox = new WriteTextBox(WriteTextBox1);
// 委托作為參數(shù),在方法WriteText通過委托運(yùn)行WriteTextBox1方法
WriteText(writeTextBox);
textBox3.Focus();
textBox3.SelectAll();
}
if (checkBox2.Checked == true)
{
textBox2.Clear();
textBox2.Refresh();
// 實(shí)例化委托 - 方法WriteTextBox2作為參數(shù)
writeTextBox = new WriteTextBox(WriteTextBox2);
// 委托作為參數(shù),在方法WriteText通過委托運(yùn)行WriteTextBox2方法
WriteText(writeTextBox);
textBox3.Focus();
textBox3.SelectAll();
}
}
/**
*我們通過WriteText方法來向文本區(qū)寫入內(nèi)容,
*它所執(zhí)行的只是抽象的”寫文本“操作,至于究竟向哪個(gè)文本框?qū)懭胛淖郑?BR> *對于編寫WriteText方法的程序來說是不知道,委托writeTextBox就像一個(gè)接口一樣,
*屏蔽了操作對象的差別(方法到底是想向文本區(qū)1寫入文本還是像文本區(qū)2寫入文本,
*現(xiàn)在我方法里面不需要去關(guān)心,
*我只需要集中在實(shí)現(xiàn)”書寫文本”這個(gè)操作,而不必糾結(jié)操作對象的選擇)。
*/
private void WriteText(WriteTextBox writetextbox)
{
string data = textBox3.Text;
for (int i = 0; i < data.Length; i++)
{
// 使用委托 - 通過委托的不同運(yùn)行不同的方法
writetextbox(data[i]);
//間歇延時(shí)
DateTime now = DateTime.Now;
while (now.AddSeconds(1) > DateTime.Now) { }
}
}
//向文本區(qū)1添加字符
private void WriteTextBox1(char ch)
{
textBox1.AppendText(ch.ToString());
}
//向文本區(qū)2添加字符
private void WriteTextBox2(char ch)
{
textBox2.AppendText(ch.ToString());
}
}
}
Form1.cs
b.效果圖:
2.委托鏈
其實(shí)委托鏈就是一個(gè)委托,只是包含了多個(gè)委托而已??赐晗旅娲a,應(yīng)該可以很明白。
a.代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
// 聲明一個(gè)委托類型,它的實(shí)例引用一個(gè)方法,該方法返回一個(gè)string類型
public delegate string DelegateTest();
public static void Main(string[] args)
{
// 用靜態(tài)方法來實(shí)例化委托
DelegateTest dtstatic = new DelegateTest(Program.method1);
// 用實(shí)例方法來實(shí)例化委托
DelegateTest dtinstance = new DelegateTest(new Program().method2);
DelegateTest dtinstance2 = new DelegateTest(new Program().method3);
// 定義一個(gè)委托鏈對象,一開始初始化為null,就是不代表任何方法(我就是我,我不代表任何人)
DelegateTest delegatechain = null;
delegatechain += dtstatic;
delegatechain += dtinstance;
delegatechain += dtinstance2;
// Environment.NewLine - 換行符
Console.WriteLine(Environment.NewLine + dtstatic() + Environment.NewLine);// 隱式調(diào)用委托
Console.WriteLine(dtstatic.Invoke() + Environment.NewLine);// 顯式調(diào)用委托
Console.WriteLine(Environment.NewLine + Test(delegatechain));//輸出字符串
Console.Read();
}
private static string method1()
{
return "這是靜態(tài)方法1";
}
private string method2()
{
throw new Exception("拋出了一個(gè)異常");
}
private string method3()
{
return "這是實(shí)例方法3";
}
// 測試調(diào)用委托的方法
private static string Test(DelegateTest chain)
{
if (chain == null)
{
return null;
}
// 用這個(gè)變量來保存輸出的字符串
StringBuilder returnstring = new StringBuilder();
// GetInvocationList方法返回一個(gè)由Delegate引用構(gòu)成的數(shù)組,
//其中每一個(gè)數(shù)組都指向鏈中的一個(gè)委托對象。
Delegate[] delegatearray = chain.GetInvocationList();
// 遍歷數(shù)組中的每個(gè)委托
foreach (DelegateTest t in delegatearray)
{
try
{
//調(diào)用委托獲得返回值
returnstring.Append(t() + Environment.NewLine);
}
catch (Exception e)//異常
{
returnstring.AppendFormat("異常從 {0} 方法中拋出, 異常信息為:{1}{2}", t.Method.Name, e.Message, Environment.NewLine);
}
}
// 把結(jié)果返回給調(diào)用者
return returnstring.ToString();
}
}
}
Program.cs
b.效果圖:

相關(guān)文章
C#實(shí)現(xiàn)軟件開機(jī)自啟動(dòng)功能(不需要管理員權(quán)限)
在本文中,我們探討了如何使用C#語言實(shí)現(xiàn)應(yīng)用程序在系統(tǒng)啟動(dòng)時(shí)自動(dòng)運(yùn)行的功能,同時(shí)避免了對管理員權(quán)限的需求,文章通過代碼示例講解的非常詳細(xì),對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2025-04-04
unity 實(shí)現(xiàn)攝像機(jī)繞某點(diǎn)旋轉(zhuǎn)一周
這篇文章主要介紹了unity 實(shí)現(xiàn)攝像機(jī)繞某點(diǎn)旋轉(zhuǎn)一周,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04
C#實(shí)現(xiàn)Winform中打開網(wǎng)頁頁面的方法
這篇文章主要介紹了C#實(shí)現(xiàn)Winform中打開網(wǎng)頁頁面的方法,涉及WinForm中WebBrowser的相關(guān)使用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-08-08
C#項(xiàng)目中跨文件調(diào)用公共類的實(shí)例方法
在本篇文章里小編給大家整理的是關(guān)于C#項(xiàng)目中如何跨文件調(diào)用公共類的知識(shí)點(diǎn)內(nèi)容,需要的朋友們學(xué)習(xí)下。2019-08-08
C#編程實(shí)現(xiàn)DataTable添加行的方法
這篇文章主要介紹了C#編程實(shí)現(xiàn)DataTable添加行的方法,結(jié)合兩個(gè)實(shí)例形式分析了C#操作DataTable實(shí)現(xiàn)動(dòng)態(tài)添加行的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-11-11
使用數(shù)字簽名實(shí)現(xiàn)數(shù)據(jù)庫記錄防篡改(Java實(shí)現(xiàn))
本文主要介紹了Java中使用數(shù)字簽名實(shí)現(xiàn)數(shù)據(jù)庫記錄防篡改的方法與步驟。具有很好的參考價(jià)值,下面跟著小編一起來看下吧2017-01-01

