我们为什么需要C#代表 [英] Why do we need C# delegates
本文介绍了我们为什么需要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,可以提供大量的执行情况向
选择
的方法。
- 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#代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文