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#实现+AOT 打造的多功能图片处理工具 ImageGlider
纯C#+AOT打造的ImageGlider,图像处理功能堆得像山,还非得标榜零依赖?ImageSharp封装得倒是挺顺溜,就是不知道这模块化架构能走多远。Web API和CLI工具有点东西,但别指望我夸太离谱。
2025-08-05 · C# · 约 1 分钟
一次小而美的重构:使用 C# 在 Avalonia 中生成真正好看的词云
重构StarBlogPublisher中词云展示功能的过程。作者对比了两个流行的C#词云库,最终选择了功能更强大的Sdcb.WordCloud。文章详细说明了如何使用该库获取词频数据并生成词云图像,并展示了重构前后的效果对比。
2025-04-26 · C# · 约 1 分钟
System.Text.Json使用中的几个常见问题
前言 以前.NetCore是不内置JSON库的,所以大家都用Newtonsoft的JSON库,而且也确实挺好用的,不过既然官方出了标准库,那更方便更值得我们多用用,至少不用每次都nuget安装Newtonsoft.Json库了。 不过日常开发使用中会有一些问题,本文记录一下解决方法,欢迎交流~ ~~(文章末尾包含小彩蛋)~~ 字符编码问题 默认的 System.Text.Json 序列化的时候会把
2022-05-27 · C# · 约 1 分钟
开发现代化的.NetCore控制台程序:(1)项目介绍以及依赖注入/配置/日志等使用细节
开发.NET Core控制台工具,依赖注入和日志整合得比Go优雅多了。哼,配置文件丝滑,但AOT?反射问题,放弃。
2023-11-10 · C# · 约 1 分钟
讨论
共 0 条加载评论中…