当前位置:网站首页>C EventHandler observer mode
C EventHandler observer mode
2022-07-23 10:48:00 【biyusr】
C# and java Compare :java Interface is used in .C# Use the delegation mechanism , When it can be used + Operator to register , Direct multicast . and java Generally, a set is used to save observers .
Publisher (Publisher)= Observed (Observable) = Event source (java Medium EventObject,C# Medium sender)
subscriber (Subscriber)= The observer (Observer)= The receiver (java In the inheritance EventLister, Interface , or Observer Interface , C# Due to the entrustment mechanism , No need to inherit interface , Directly by EventHandler Implement callback methods )
When something concerned by other classes or objects happens , Classes or objects can notify them through events . send out ( Or trigger ) The class of events is called “ publisher ”, receive ( Or processing ) The class of events is called “ subscriber ”. In a typical C# Windows Form or Web In the application , Subscribable by control ( Such as buttons and list boxes ) Events triggered by . You can use Visual C# Integrated development environment (IDE) To browse the events published by the control , Select the event to process .IDE Empty event handler methods and code for subscribing to events will be automatically added .
EventHandler by C# Predefined delegates in , Handler methods dedicated to events that represent events that do not generate data .
public delegate void EventHandler(Object sender, EventArgs e)The event has the following characteristics :
1. The publisher determines when the event is triggered , The subscriber determines what action to perform in response to the event .
2. An event can have multiple subscribers . A subscriber can handle multiple events from multiple publishers .
3. Events without subscribers will never be called .
4. Events are usually used to inform users of actions ( Such as : Button click or menu selection actions in the graphical user interface ).
5. If an event has multiple subscribers , When this event is triggered , Multiple event handlers will be called synchronously . To invoke events asynchronously , See calling synchronous methods asynchronously .
6. You can use events to synchronize threads .
7. stay .NET Framework Class library , Events are based on EventHandler Commission and EventArgs The base class .
The following example demonstrates the above steps , It will be customized EventArgs Classes and EventHandler Used as an event type .
namespace ConsoleApplication2{using System;using System.Collections.Generic;// Customize an event class to save event informationpublic class CustomEventArgs : EventArgs{public CustomEventArgs(string s){message = s;}private string message;public string Message{get { return message; }set { message = value; }}}// Class of broadcast eventsclass Publisher{// Use EventHandler<T> Declare an eventpublic event EventHandler<CustomEventArgs> RaiseCustomEvent;// This method is to do something . Then trigger an event .public void DoSomething(){//DoSomething…………// You can also trigger events before , Execute some other codeOnRaiseCustomEvent(new CustomEventArgs("Did something,hi This is the news of the event "));}// Use virtual methods , Let subclasses override .to allow derived classes to override the event invocation behaviorprotected virtual void OnRaiseCustomEvent(CustomEventArgs e){// Define a local variable , The last subscriber has been prevented from just checking null Unsubscribe afterEventHandler<CustomEventArgs> handler = RaiseCustomEvent;// without subscriber ( The observer ), The delegate object will be nullif (handler != null){// Format event messages Stringe.Message += String.Format(" at {0}", DateTime.Now.ToString());// This is the most important sentence .// At this time handler It is already a multicast delegation ( If there are multiple subscribers or observers registered ).// Since it is a multicast delegation , You can call each Callback function ( Since it is a callback function , The actual execution is determined by the subscriber class ).// Here comes a this, On behalf of Event source ( Or publisher or Observed They all mean the same thing )handler(this, e);}}}// Class used to register eventsclass Subscriber{private string id;public Subscriber(string ID, Publisher pub){id = ID;// Register this action , Subscribers should take the initiative , And you can cancel the registration laterpub.RaiseCustomEvent += HandleCustomEvent;}// Implement callback function . After the event , What kind of operation to perform . Here is just a simple print message .void HandleCustomEvent(object sender, CustomEventArgs e){// This is the actual operation .Console.WriteLine(id + " received this message: {0}", e.Message);}}class Class1{static void Main(string[] args){Publisher pub = new Publisher();Subscriber sub1 = new Subscriber("sub1", pub);Subscriber sub2 = new Subscriber("sub2", pub);// Call this method to generate eventspub.DoSomething();Console.WriteLine("Press Enter to close this window.");Console.ReadLine();}}}
边栏推荐
- Chapter2 Standard Output
- PXE remote installation and kickstart unattended installation technical documents
- 04_ UE4 advanced_ Introduction to physical collision and firing fireballs
- Data warehouse: workflow design and Optimization Practice
- Basic knowledge of C language (I)
- 添加信任列表
- 构建人工智能产品/业务的两种策略(by Andrew Ng)
- 为什么我们无法写出真正可重用的C#/F#代码?
- Solve the Chinese garbled code of post request and get request in servlet
- 《Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks》论文阅读
猜你喜欢

阿里云如何将一个域名解析到另一个域名上

JMeter record the BeanShell written into excel instance caused by an automatic data generation

CloudCompare&PCL 点云点匹配(基于点到面的距离)

Self operation and maintenance: a new sample of it operation and maintenance services in Colleges and Universities

Analysis of network security level protection 2.0 standard

添加信任列表

C# IValueConverter接口用法举例

When flutter runs flutter pub get, it reports an error: "the client does not have the required privileges“

Clion + mingw64 configure C language development environment visual studio installation

C語言基礎知識梳理(一)
随机推荐
DPDK 交叉编译基本流程
C# 客户端程序调用外部程序的3种实现方法
Clion + mingw64 configure C language development environment visual studio installation
Common neural network parameters and calculations
Anaconda虚拟环境下安装opencv报错的问题
MapReduce advanced
How Alibaba cloud resolves a domain name to another domain name
MySQL index operation
PXE remote installation and kickstart unattended installation technical documents
What is file management software? Why do you need it?
推荐一款 Shell 装逼神器,已开源!网友:真香。。。
Warning lnk4210 reports an error when writing the driver
常见神经网络参数量与计算量
Script of Nacos current limiting query
【Warning】YOLOV5训练时的ignoring corrupt image/label: [Errno 2].....,无法全部训练数据集,快速带你解决它
Antlr4 introductory learning (I): Download and test
Chapter 4 Executing Commands
软件测试基础篇—测试用例的设计方法
LeetCode刷题--点滴记录023
C# EventHandler观察者模式