C# Learning (2): Various Ways to Use Anonymous Methods and Delegates
Preface Last time I briefly introduced the concept and usage of delegates. Today I'll continue, and introduce the concept of anonymous methods. Anonymous methods exist in many languages, such as Python, JS, and Java 8. Especially JS — frontend folks may have suffered greatly from JS callback hell, and anonymous methods played an indispensable role in that. JS anonymous methods look like this: I haven't used lambda yet, because I want to introduce lambda in the next post. document.querySelector('.btn').onclick = function () {
目录7 个章节
Preface
Last time I briefly introduced the concept and usage of delegates. Today I'll continue, and introduce the concept of anonymous methods. Anonymous methods exist in many languages, such as Python, JS, and Java 8. Especially JS — frontend folks may have suffered greatly from JS callback hell, and anonymous methods played an indispensable role in that.
JS anonymous methods look like this: I haven't used lambda yet, because I want to introduce lambda in the next post.
document.querySelector('.btn').onclick = function () { };
Python is roughly like this:
max = lambda a : a + 1
A Few Concepts
Instantiating Delegates
Once a delegate type is declared, a delegate object must be created using the new keyword, and it is associated with a specific method. When creating a delegate, the argument passed to the new statement is written like a method call, but without parameters.
Multicast Delegates
Delegate objects can be combined using the "+" operator. A combined delegate invokes the two delegates it combines. Only delegates of the same type can be combined. The "-" operator can be used to remove component delegates from a combined delegate. Using this useful feature of delegates, you can create an invocation list of methods to be called when the delegate is invoked. This is called multicast (multicasting) of delegates, also known as group multicast.
Events
An event (Event) is basically a user action, such as a key press, click, mouse movement, etc., or some notification information, such as a system-generated notification. Applications need to respond to events when they occur. For example, interrupts. C# uses the event mechanism to implement communication between threads.
Events are declared and raised in a class, and are associated with event handlers through delegates in the same class or other classes. The class that contains the event is used to publish the event. This is called the publisher class. Other classes that receive the event are called subscriber classes. Events use the publisher-subscriber model.
- A publisher is an object that contains event and delegate definitions. The association between the event and the delegate is also defined in this object. An object of the publisher class invokes this event and notifies other objects.
- A subscriber is an object that receives the event and provides an event handler. The delegate in the publisher class calls the method (event handler) in the subscriber class.
I'll record the detailed usage of events in later notes.
Here's the Code
First, here's the notes code, with detailed comments inside:
using System;
namespace DelegateAndEvent
{
class Program
{
delegate void voidDelegate();
delegate int intDelegate();
delegate int doubleParamsDelegate(int num1, int num2);
static void Main(string[] args)
{
// 定义一个多播委托
voidDelegate d1 = T1;
d1 += T2;
d1 += T3;
d1 += T4;
// 执行委托
// 会同时执行t1,t2,t3,t4四个方法
d1();
intDelegate d2 = Q1;
d2 += Q2;
d2 += Q3;
Console.WriteLine("");
Console.WriteLine("");
// 执行
// 会得到最后一个返回值,
Console.WriteLine(d2());
// 两种委托赋值方式
d1 = T1;
d1 = new voidDelegate(T1);
// 利用委托将函数作为参数传递
Func(T1);
Func(T2);
// 匿名方法
// 定义匿名方法委托
voidDelegate anonymousMethod = delegate { Console.WriteLine("hello"); };
// 作为参数传递
Func(anonymousMethod);
// 定义有参数和返回值的匿名方法
doubleParamsDelegate max = delegate(int num1, int num2) { return num1 > num2 ? num1 : num2; };
// 换成lambda表达式
max = (a, b) => a > b ? a : b;
max(1, 2);
}
static void T1()
{
Console.WriteLine("1");
}
static void T2()
{
Console.WriteLine("2");
}
static void T3()
{
Console.WriteLine("3");
}
static void T4()
{
Console.WriteLine("4");
}
static int Q1()
{
return 1;
}
static int Q2()
{
return 2;
}
static int Q3()
{
return 3;
}
static void Func(voidDelegate func)
{
func();
}
}
}
That's it. C#'s anonymous methods are just new-ing a delegate, but basically nobody uses this, because even ancient versions of C# already supported lambda expressions. Lambda is a convenient way to define anonymous methods, and it's elegant too. I'll record the usage of lambda expressions in the next post.
This article mainly records various ways to use delegates, such as passing values, events, passing function parameters, etc.
There is more practice code waiting for me to organize and put on GitHub.
Welcome to Discuss
For discussion, please leave a message in the WeChat official account backend. I'll reply to every message~
- WeChat official account: 画星星高手
- Coding livestream: https://live.bilibili.com/11883038
- Zhihu: https://www.zhihu.com/people/dealiaxy
- Jianshu: https://www.jianshu.com/u/965b95853b9f
_EOF_
C# Learning (2): Various Ways to Use Anonymous Methods and Delegates
- 本文作者:
- 程序设计实验室
- 版权声明:
- 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
相关文章
C#学习(一)委托的概念和使用
前言 C#学习系列是根据我以前的笔记整理出来复习,顺便发一下文章做个记录。 先引用一个介绍: C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针。委托(Delegate) 是存有对某个方法的引用的一种引用类型变量。引用可在运行时被改变。 委托(Delegate)特别用于实现事件和回调方法。所有的委托(Delegate)都派生自 System.Delegate 类。 根据使用其他
2021-12-18 · C# · 约 1 分钟
C#中的Attribute与Python-TypeScript的装饰器是同个东西吗
前言 最近成功把「前端带师」带入C#的坑~~(实际是前端带师开始从cocos转unity游戏开发了)~~ 某天,「前端带师」看到这段代码后问了个问题:[这个是装饰器]? [HttpGet] public Response Get() { return ... } 我第一反应觉得不是,这玩意在C#中叫“特性”(英文名Attribute,下文统称为特性),在Java中叫注解,虽然写法和Pyth
2022-06-26 · C# · 约 1 分钟
开发现代化的.NetCore控制台程序:(2)创建一个C#项目模板
又一个.NetCore模板?FluentConsole.Templates,一键生成骨架,包含DI、日志、配置。安装?dotnet new install,然后dotnet new flu-cli -n MyProject。太简单了吧,谁在乎?
2023-11-10 · C# · 约 1 分钟
纯 C#实现+AOT 打造的多功能图片处理工具 ImageGlider
纯C#+AOT打造的ImageGlider,图像处理功能堆得像山,还非得标榜零依赖?ImageSharp封装得倒是挺顺溜,就是不知道这模块化架构能走多远。Web API和CLI工具有点东西,但别指望我夸太离谱。
2025-08-05 · C# · 约 1 分钟
讨论
共 0 条加载评论中…