C# 實例解析事件委托之EventHandler

概述

? ? ?事件屬于委托的一個子集,像我們平時界面上的鼠標點擊按鈕后響應事件、事件的發布和訂閱等都需要用到委托.通過委托可以很好的實現類之間的解耦好。事件委托EventHandler的

函數原型如下:delegate 表示這個個委托,事件委托沒有返回值,有兩個入參,sender是事件觸發的對象,e是一個泛型的事件類型參數

public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);

用法舉例

用法舉例1:窗體關閉事件

public void Cancel(object obj, bool e){if (e){sw.AppendLine("try clsoe window");}else{sw.AppendLine("clsoe window is cancel");}}
//事件委托1,事件是委托的子集EventHandler<bool> windowTryClose = Cancel;windowTryClose(this, false);

這里在定義了一個委托EventHandler<bool>,將方法Cancel委托給他,然后嗲用委托執行。

注意:EventHandler<bool> windowTryClose = Cancel;是
EventHandler<bool> windowTryClose = new EventHandler<bool>(Cancel);的簡寫

傳入的參數是false,所以運行結果:

clsoe window is cancel

用法舉例2 :按鈕點擊事件

//事件委托2Button button = new Button();button.ClickEvent += Button_Click;button.ClickAction();
public void Button_Click(Object sender, EventArgs args){sw.AppendLine("這是按鈕點擊事件");}
public class Button{public EventHandler ClickEvent;public void ClickAction(){ClickEvent.Invoke(this, new EventArgs());}}

這里主要是寫了按鈕點擊事件的一個委托,一般在定義事件委托時前面可以用event去修飾,我這里省略了,

用法舉例3 :事件發布與訂閱

//事件委托3var myPublishEventArgs = new PublishEvent();_ = new SubscribeEvent(myPublishEventArgs);myPublishEventArgs.Publish();
public class MyPublishEventArgs : EventArgs{public string InfoString { get; set; }}public class PublishEvent{public event EventHandler<MyPublishEventArgs> OnPublish;public void Publish(){OnPublish?.Invoke(this, new MyPublishEventArgs() { InfoString = "hello" });}}public class SubscribeEvent{public SubscribeEvent(PublishEvent publishEvent){publishEvent.OnPublish += Subscribe;}public void Subscribe(Object sender, MyPublishEventArgs args){MessageBox.Show($"我接收到的消息是:{args.InfoString}");}}

這里封裝了幾個類,MyPublishEventArgs是我要發送的事件,MyPublishEventArgs這個類是發布者,SubscribeEvent這個是訂閱者,主要訂閱事件一定要放在發布前,這樣才能成功接收到事件.

委托部分這里就講解完事了,全部源碼如下:

using PropertyChanged;
using System;
using System.Text;
using System.Threading;
using System.Windows;namespace Caliburn.Micro.Hello.ViewModels
{[AddINotifyPropertyChangedInterface]public class DelegateViewModel : Screen,IViewModel{public string ResultString { get; set; }delegate int DelegateM(string a, string b);//聲明,可以有返回值也可以沒有StringBuilder sw = new StringBuilder();public DelegateViewModel(){DisplayName = "DelegateTest";}public void Test(){sw.AppendLine($"【Delegate測試】執行線程id:{Thread.CurrentThread.ManagedThreadId}");//func用法1//Func<string, string, int> func = new Func<string, string, int>(p.StringAddA);Func<string, string, int> func = StringAddA;//簡寫var result = func.Invoke("3", "5");//可以簡化為func("3", "5")sw.AppendLine($"【func用法1】func返回結果是:{result}");//func用法2,用lamda表達式簡化寫法,通過+=注冊實現多播委托func += (a, b) =>{return int.Parse(a) - int.Parse(b);};sw.AppendLine($"【func用法2】func返回結果是:{func("3", "5")}");//Action用法//Action<string, string> action = new Action<string, string>(p.StringAddB);Action<string, string> action = StringAddB;//簡寫IAsyncResult asyncResult = action.BeginInvoke("3", "5", null, null);//action("3", "5"),BeginInvoke異步執行,即:開啟新現成處理StringAddBaction.EndInvoke(asyncResult);//阻塞委托,直到執行完成if (asyncResult.IsCompleted){sw.AppendLine($"【Action用法】當前異步委托線程已執行完成");}Test(func, action);//將方法委托后轉化為參數進行傳遞//delegate用法//DelegateM delegateM = new DelegateM(p.StringAddA);DelegateM delegateM = StringAddA;//簡寫sw.AppendLine($"【delegate用法】delegate返回結果是:{delegateM("3", "5")}");//事件委托1,事件是委托的子集EventHandler<bool> windowTryClose = new EventHandler<bool>(Cancel);windowTryClose(this, false);//事件委托2Button button = new Button();button.ClickEvent += Button_Click;button.ClickAction();//事件委托3var myPublishEventArgs = new PublishEvent();_ = new SubscribeEvent(myPublishEventArgs);myPublishEventArgs.Publish();ResultString = sw.ToString();}public int StringAddA(string a, string b){return int.Parse(a) + int.Parse(b);}public void StringAddB(string a, string b){sw.AppendLine($"【Action用法】Action執行線程id:{Thread.CurrentThread.ManagedThreadId}");sw.AppendLine($"【Action用法】Action執行結果:{(int.Parse(a) + int.Parse(b))}");}public void Test(Func<string, string, int> f, Action<string, string> a){a.Invoke(f.Invoke("3", "5").ToString(), "5");}public void Cancel(object obj, bool e){if (e){sw.AppendLine("try clsoe window");}else{sw.AppendLine("clsoe window is cancel");}}public void Button_Click(Object sender, EventArgs args){sw.AppendLine("這是按鈕點擊事件");}public void MyEvent(Object sender, EventArgs args){sw.AppendLine("這是按鈕點擊事件");}}public class Button{public EventHandler ClickEvent;public void ClickAction(){ClickEvent.Invoke(this, new EventArgs());}}public class MyPublishEventArgs : EventArgs{public string InfoString { get; set; }}public class PublishEvent{public event EventHandler<MyPublishEventArgs> OnPublish;public void Publish(){OnPublish?.Invoke(this, new MyPublishEventArgs() { InfoString = "hello" });}}public class SubscribeEvent{public SubscribeEvent(PublishEvent publishEvent){publishEvent.OnPublish += Subscribe;}public void Subscribe(Object sender, MyPublishEventArgs args){MessageBox.Show($"我接收到的消息是:{args.InfoString}");}}
}

運行結果:

393f7aaf9783330e2f7c5b093f8e832e.png

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/280863.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/280863.shtml
英文地址,請注明出處:http://en.pswp.cn/news/280863.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

C# HttpWebRequest post 數據與上傳圖片到server

主體 Dictionary<string, object> postData new Dictionary<string, object>(); string fileFullPath this.imgFullPath;if (!File.Exists(fileFullPath)){Message(Error, "file not exist: " fileFullPath);goto EndGetPost;}// 先定義一個…

多虧了Google相冊,如何一鍵釋放Android手機上的空間

Let’s be real here: modern smartphones have limited storage. While they’re coming with a lot more than they used to, it’s easy to fill 32GB without even realizing it. And with today’s high-end cameras, well, pictures and videos can quickly consume a bi…

用window.location.href實現頁面跳轉

在寫ASP.Net程序的時候&#xff0c;我們經常遇到跳轉頁面的問題&#xff0c;我們經常使用Response.Redirect &#xff0c;如果客戶要在跳轉的時候使用提示&#xff0c;這個就不靈光了&#xff0c;如&#xff1a;Response.Write("<script>alert(恭喜您&#xff0c;注…

(一)使用appium之前為什么要安裝nodejs???

很多人在剛接觸appium自動化時&#xff0c;可能會像我一樣&#xff0c;按照教程搭建好環境后&#xff0c;卻不知道使用appium之前為什么要用到node.js&#xff0c;nodejs到底和appium是什么關系&#xff0c;對nodejs也不是很了解&#xff0c;接下來我和大家一起理解一下他們之間…

WPF效果第二百零四篇之自定義更新控件

好久沒有更新文章,今天抽空來分享一下最近玩耍的自定義控件;里面包含了自定義控件、依賴屬性和路由事件;來看看最終實現的效果:1、先來看看前臺Xaml布局和綁定:<Style TargetType"{x:Type Cores:UploadWithProgressControl}"><Setter Property"Templat…

u3d 逐個點運動,路徑運動。 U3d one by one, path motion.

u3d 逐個點運動&#xff0c;路徑運動。 U3d one by one, path motion. 作者&#xff1a;韓夢飛沙 Author&#xff1a;han_meng_fei_sha 郵箱&#xff1a;313134555qq.com E-mail: 313134555 qq.com 逐個點運動&#xff0c;路徑運動。 Im going to do some motion and path. 如果…

小米凈水器底部漏水_漏水傳感器:您可能沒有的最容易被忽視的智能家居設備...

小米凈水器底部漏水While most smarthome products are aimed at convenience, there’s one smarthome device that’s actually quite useful, possibly saving you headaches and ton of money: the trusty water leak sensor. 雖然大多數智能家居產品都旨在提供便利&#x…

Unity3D筆記十 游戲元素

一、地形 1.1 樹元素 1.2 草元素 二、光源 2.1 點光源 點光源&#xff08;Point Light&#xff09;&#xff1a;好像包圍在一個類似球形的物體中&#xff0c;讀者可將球形理解為點光源的照射范圍&#xff0c;就像家里的燈泡可以照亮整個屋子一樣。創建點光源的方式為在Hierarch…

BZOJ3511: 土地劃分

【傳送門&#xff1a;BZOJ3511】 簡要題意&#xff1a; 給出n個點&#xff0c;m條邊&#xff0c;每個點有A和B兩種形態&#xff0c;一開始1為A&#xff0c;n為B 給出VA[i]和VB[i]&#xff0c;表示第i個點選擇A和B形態的價值 每條邊給出x,y,EA,EB,EC&#xff0c;表示如果x和y都為…

facebook 文本分類_如何禁用和自定義Facebook的通知,文本和電子郵件

facebook 文本分類Facebook is really keen on keeping you on their platform. One of the ways they do that is by sending you notifications whenever the tiniest thing happens. And you won’t just see them on the site—Facebook will also notify you by email, wi…

django06: ORM示例2--uer 與file

存放路徑&#xff1a;https://git.lug.ustc.edu.cn/ 筆記 外鍵與多鍵 path models.ForeignKey(to"Path")file models.ManyToManyField(to"File") code 處理方式 new_path request.POST.get("new_path",None)models.File.objects.create(…

Error opening terminal: xterm-256color

在使用gdb調試linux內核時&#xff0c;提示如下錯誤&#xff1a; arm-none-linux-gnueabi-gdb --tui vmlinux Error opening terminal: xterm-256color. 解決辦法&#xff1a; 1、 edit your .bash_profile file vim .bash_profile 2、commnet #export TERMxterm-256colo…

四種簡單的排序算法

四種簡單的排序算法 我覺得如果想成為一名優秀的開發者&#xff0c;不僅要積極學習時下流行的新技術&#xff0c;比如WCF、Asp.Net MVC、AJAX等&#xff0c;熟練應用一些已經比較成熟的技術&#xff0c;比如Asp.Net、WinForm。還應該有著牢固的計算機基礎知識&#xff0c;比如數…

Xampp修改默認端口號

為什么80%的碼農都做不了架構師&#xff1f;>>> Xampp默認的端口使用如下&#xff1a; Httpd使用80端口 Httpd_ssl使用443端口 Mysql使用3306端口 ftp使用21端口 但是&#xff0c;在如上端口被占用的情況下&#xff0c;我們可以通過修改xampp默認端口的方法&…

為什么csrss進程有三個_什么是客戶端服務器運行時進程(csrss.exe),為什么在我的PC上運行它?...

為什么csrss進程有三個If you have a Windows PC, open your Task Manager and you’ll definitely see one or more Client Server Runtime Process (csrss.exe) processes running on your PC. This process is an essential part of Windows. 如果您使用的是Windows PC&…

使用c#的 async/await編寫 長時間運行的基于代碼的工作流的 持久任務框架

持久任務框架 &#xff08;DTF&#xff09; 是基于async/await 工作流執行框架。工作流的解決方案很多&#xff0c;包括Windows Workflow Foundation&#xff0c;BizTalk&#xff0c;Logic Apps, Workflow-Core 和 Elsa-Core。最近我在Dapr 的倉庫里跟蹤工作流構建塊的進展時&a…

bat批處理筆記

變量 1.CMD窗口變量&#xff0c;變量名必須用單%引用&#xff08;即&#xff1a;%variable&#xff09; 外部變量&#xff0c;是系統制定的&#xff0c;只有9個&#xff0c;專門保存外部參數的&#xff0c;就是運行批處理時加的參數。只有 %1 %2 %3 %4 ...... %9。 在bat內直…

多目標跟蹤(MOT)論文隨筆-SIMPLE ONLINE AND REALTIME TRACKING (SORT)

轉載請標明鏈接&#xff1a;http://www.cnblogs.com/yanwei-li/p/8643336.html 網上已有很多關于MOT的文章&#xff0c;此系列僅為個人閱讀隨筆&#xff0c;便于初學者的共同成長。若希望詳細了解&#xff0c;建議閱讀原文。 本文是使用 tracking by detection 方法進行多目標…

明日大盤走勢分析

如上周所述&#xff0c;大盤在4與9號雙線壓力下&#xff0c;上攻乏力。今天小幅下跌0.11%&#xff0c;漲511&#xff0c;平76&#xff0c;跌362&#xff0c;說明個股還是比較活躍&#xff0c;而且大盤上漲趨勢未加改變&#xff0c;只是目前攻堅&#xff0c;有點缺乏外部的助力。…

android EventBus 3.0 混淆配置

2019獨角獸企業重金招聘Python工程師標準>>> https://github.com/greenrobot/EventBus 使用的這個庫在github的官網README中沒有寫明相應混淆的配置. 經過對官網的查詢&#xff0c;在一個小角落還是被我找到了。 -keepattributes *Annotation* -keepclassmembers …