本文介绍了为什么我们需要 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:

  1. 您希望使用单个委托来调用一系列方法,而无需编写大量方法调用.
  2. 您想优雅地实现基于事件的系统.
  3. 您想调用两个签名相同但位于不同类中的方法.
  4. 您想将方法作为参数传递.
  5. 您不想像在 LINQ 中那样编写大量多态代码,您可以为 Select 方法提供大量实现.
  1. You want to call series of method by using single delegate without writing lot of method calls.
  2. You want to implement event based system elegantly.
  3. You want to call two methods same in signature but reside in different classes.
  4. You want to pass method as a parameter.
  5. You don't want to write lot of polymorphic code like in LINQ , you can provide lot of implementation to the Select method.

这篇关于为什么我们需要 C# 委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:04