当前位置:网站首页>C # basic 1-events and commissions
C # basic 1-events and commissions
2022-07-28 20:54:00 【W.C.Zeng】
entrust
Delegate is simply understood as a variable of function type ( Reference type ), Represents a reference to a method .
Website to explain delegate
Define delegate type
public delegate void KeyDelegate(string key);
Define the processing function of the corresponding delegate type
public static void PrintString(string key)
{
Console.WriteLine(key);
}
Instantiate variables of delegate type
KeyDelegate keyAevent = new KeyDelegate(DelegateFunc.PrintString);
A delegate can bind multiple event handlers
multiEvent += new KeyDelegate(DelegateFunc.PrintString2);
Use delegate variables , Call all the event handling functions corresponding to the delegate
multiEvent("B");
The difference between delegation and interface
Definition
Interface (interface) It is a set that constrains what functions a class should have , Constrains which methods a class should have , It is convenient for class management and extension , Using interfaces can also solve the single inheritance problem of classes .
entrust (delegate) Is a collection of methods , Using delegates, you can operate on this set of methods , Such as += .
Applicable scenario
Use the interface in the following cases :
- Has inherited a class , You can no longer inherit other classes , But I hope to continue to expand other functions
- When completely abstract
- When multi person collaboration requires the function of constraint class
Use delegates when :
- In the first two processes of event processing : Defining events ( Commissioned by using )、 The binding event ( The method set corresponding to the operation delegate )、 Event handler 、 Call event
event
Event is a package of delegation
Events are variables of delegate type
Events use Release - subscribe Model of , The publisher contains Event and delegate definitions The connection between the event and the Commission , Subscriber accept Event and provide event handling
Declaration delegation
public delegate void KeyDelegate(string key);
Claim event
public static event KeyDelegate? keyEvent;
The binding event
EventHandler.keyEvent += DelegateFunc.PrintString2;
Define event handling functions ( Corresponding to the delegate type )
public static void PrintString2(string key)
{
Console.WriteLine("-" + key + "-");
}
Call event
keyEvent?.Invoke(key);
Add
Another kind public static event Action<string> keyEvent; The event definition of , among Action<T> Is the abbreviation of delegation , You can quickly declare event variables of delegate types , Unlike the traditional entrusted writing , You need to declare the delegate type first , Then instantiate a delegate variable with the delegate type to use
Complete code
using System;
// 1.1 Declare a delegate type KeyDelegate
public delegate void KeyDelegate(string key);
class DelegateFunc
{
// 1.2 Declare the method corresponding to the delegate type Return value 、 Parameter list and delegate type KeyDelegate bring into correspondence with
public static void PrintString(string key)
{
Console.WriteLine(key);
}
// 2.3 Event handler
public static void PrintString2(string key)
{
Console.WriteLine("-" + key + "-");
}
}
public static class EventHandler
{
// 2.1 Before declaring the event , A delegate type must be declared in advance for example KeyDelegate
public static event KeyDelegate? keyEvent;
// 2.4 Call event
public static void CallKeyEvent(string key)
{
keyEvent?.Invoke(key);
}
}
class Program
{
static void Main()
{
// 1.3 Instantiate a variable of delegate type keyAevent , Corresponding to the delegated function DelegateFunc.PrintString
KeyDelegate keyAevent = new KeyDelegate(DelegateFunc.PrintString);
KeyDelegate multiEvent;
multiEvent = keyAevent;
// 1.4 A delegate can use += The operator Bind multiple event handlers
multiEvent += new KeyDelegate(DelegateFunc.PrintString2);
// 2.2 The binding event
EventHandler.keyEvent += DelegateFunc.PrintString2;
while (true)
{
ConsoleKeyInfo key = Console.ReadKey();
switch (key.Key)
{
case ConsoleKey.A:
// 1.4 aA
keyAevent("A");
break;
case ConsoleKey.B:
// 1.4 bB
// 1.4 -B-
multiEvent("B");
break;
case ConsoleKey.C:
// 2.4 c-C-
EventHandler.CallKeyEvent("C");
break;
case ConsoleKey.Q:
Console.Clear();
return;
default:
Console.WriteLine();
break;
}
}
}
}
边栏推荐
- Establishment of flask static file service
- [server data recovery] HP StorageWorks series storage RAID5 two disk failure offline data recovery case
- 有奖征文 | 2022 云原生编程挑战赛征稿活动开启
- Redis入门一:Redis实战读书笔记
- 关于正则的两道笔试面试题
- 7/27 训练日志(位运算+后缀数组)
- Dynamic planning: code summary of knapsack problem template
- Teach you unity scene switching progress bar production hand in hand
- LVS+KeepAlived高可用部署实战应用
- Space shooting Lesson 10: score (painting and writing)
猜你喜欢

How can enterprises successfully complete cloud migration?

JS fly into JS special effect pop-up login box

Unity makes prefabricated bodies with one key and modifies prefabricated bodies with one key

一文了解 Rainbond 云原生应用管理平台

Three steps to teach you unity serial communication

太空射击第13课: 爆炸效果

“当你不再是程序员,很多事会脱离掌控”—— 对话全球最大独立开源公司SUSE CTO...

Subcontracting loading of wechat applet

Unity performance optimization

What is data center? What value does the data center bring_ Light spot technology
随机推荐
System. ArgumentException: Object of type ‘System. Int64‘ cannot be converted to type ‘System.Int32‘
Introduction to redis II: RedHat 6.5 installation and use
Beautiful blue background form input box style
Space shooting lesson 09: elf animation
华为云数字资产链,“链”接数字经济无限精彩
JS picture hanging style photo wall JS special effect
Unity gets which button (toggle) is selected under togglegroup
Sorting out problems in interface endpoint testing practice using Supertest
Huawei cloud digital asset chain, "chain" connects the digital economy, infinite splendor
Fragment中使用ViewPager滑动浏览页面
SQL audit tool self introduction owls
Pl515 SOT23-5 single / Dual Port USB charging protocol port controller Parkson electronic agent
js图表散点图例子
Use order by to sort
prometheus配置alertmanager完整过程
Redis 3.0 source code analysis - data structure and object SDS list Dict
User and group and authority management
Teach you unity scene switching progress bar production hand in hand
Yyds dry inventory interview must brush top101: every k nodes in the linked list are turned over
Database tuning - connection pool optimization