Why do we need C# delegates(为什么我们需要 C# 委托)
本文介绍了为什么我们需要 C# 委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我似乎一直不明白为什么我们需要代表?我知道它们是持有方法引用的不可变引用类型,但为什么我们不能直接调用该方法,而不是通过委托调用它?
I never seem to understand why we need delegates? I know they are immutable reference types that hold reference of a method but why can't we just call the method directly, instead of calling it via a delegate?
谢谢
推荐答案
当然你可以直接在对象上调用方法,但是考虑以下场景:
Of course you can call method directly on the object but consider following scenarios:
- 您希望使用单个委托来调用一系列方法,而无需编写大量方法调用.
- 您想优雅地实现基于事件的系统.
- 您想调用两个签名相同但位于不同类中的方法.
- 您想将方法作为参数传递.
- 您不想像在 LINQ 中那样编写大量多态代码,您可以为
Select方法提供大量实现.
- You want to call series of method by using single delegate without writing lot of method calls.
- You want to implement event based system elegantly.
- You want to call two methods same in signature but reside in different classes.
- You want to pass method as a parameter.
- You don't want to write lot of polymorphic code like in LINQ , you can provide lot of implementation to the
Selectmethod.
这篇关于为什么我们需要 C# 委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:为什么我们需要 C# 委托
基础教程推荐
猜你喜欢
- 如果条件可以为空 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 将数据集转换为列表 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
