c#委托學(xué)習(xí)示例分享
1.委托
總的來(lái)說(shuō),委托是一個(gè)類,它定義了方法的類型,使得可以將方法當(dāng)作另一個(gè)方法的參數(shù)來(lái)進(jìn)行傳遞,這種將方法動(dòng)態(tài)地賦給參數(shù)的做法,可以避免在程序中大量使用If-Else(Switch)語(yǔ)句,同時(shí)使得程序具有更好的可擴(kuò)展性。所以,引入委托后,編程人員可以把方法的引用封裝在委托對(duì)象中,然后把委托對(duì)象傳遞給需要引用方法。調(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通過(guò)委托運(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通過(guò)委托運(yùn)行WriteTextBox2方法
WriteText(writeTextBox);
textBox3.Focus();
textBox3.SelectAll();
}
}
/**
*我們通過(guò)WriteText方法來(lái)向文本區(qū)寫入內(nèi)容,
*它所執(zhí)行的只是抽象的”寫文本“操作,至于究竟向哪個(gè)文本框?qū)懭胛淖郑?BR> *對(duì)于編寫WriteText方法的程序來(lái)說(shuō)是不知道,委托writeTextBox就像一個(gè)接口一樣,
*屏蔽了操作對(duì)象的差別(方法到底是想向文本區(qū)1寫入文本還是像文本區(qū)2寫入文本,
*現(xiàn)在我方法里面不需要去關(guān)心,
*我只需要集中在實(shí)現(xiàn)”書寫文本”這個(gè)操作,而不必糾結(jié)操作對(duì)象的選擇)。
*/
private void WriteText(WriteTextBox writetextbox)
{
string data = textBox3.Text;
for (int i = 0; i < data.Length; i++)
{
// 使用委托 - 通過(guò)委托的不同運(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è)委托而已。看完下面代碼,應(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)方法來(lái)實(shí)例化委托
DelegateTest dtstatic = new DelegateTest(Program.method1);
// 用實(shí)例方法來(lái)實(shí)例化委托
DelegateTest dtinstance = new DelegateTest(new Program().method2);
DelegateTest dtinstance2 = new DelegateTest(new Program().method3);
// 定義一個(gè)委托鏈對(duì)象,一開始初始化為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";
}
// 測(cè)試調(diào)用委托的方法
private static string Test(DelegateTest chain)
{
if (chain == null)
{
return null;
}
// 用這個(gè)變量來(lái)保存輸出的字符串
StringBuilder returnstring = new StringBuilder();
// GetInvocationList方法返回一個(gè)由Delegate引用構(gòu)成的數(shù)組,
//其中每一個(gè)數(shù)組都指向鏈中的一個(gè)委托對(duì)象。
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#修改及重置電腦密碼DirectoryEntry實(shí)現(xiàn)方法
這篇文章主要介紹了C#修改及重置電腦密碼DirectoryEntry實(shí)現(xiàn)方法,實(shí)例分析了C#修改及重置電腦密碼的相關(guān)技巧,需要的朋友可以參考下2015-05-05WPF自定義TreeView控件樣式實(shí)現(xiàn)QQ聯(lián)系人列表效果
TreeView控件在項(xiàng)目中使用比較頻繁,下面這篇文章主要給大家介紹了關(guān)于WPF自定義TreeView控件樣式實(shí)現(xiàn)QQ聯(lián)系人列表效果的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面來(lái)一起看看吧。2018-04-04C#控件picturebox實(shí)現(xiàn)圖像拖拽和縮放
這篇文章主要為大家詳細(xì)介紹了C#控件picturebox實(shí)現(xiàn)圖像拖拽和縮放,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-09-09Unity?UGUI的EventSystem事件系統(tǒng)組件介紹使用
這篇文章主要為大家介紹了Unity?UGUI的EventSystem事件系統(tǒng)組件介紹使用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07