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
Select
method.
这篇关于为什么我们需要 C# 委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:为什么我们需要 C# 委托


基础教程推荐
猜你喜欢
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01