且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我们在C#中使用委托代替函数

更新时间:2022-10-16 18:38:43

粗略地说委托就像一个函数指针,这是间接调用方法。

例如,请参阅我对另一个问题的解决方案:如何使用循环调用多个方法,请帮助 [ ^ ]。

更多细节,例如,在这里: oop - 我在哪里使用代表? - 堆栈溢出 [ ^ ]。


然后可以将委托对象传递给可以调用引用方法的代码,而无需在编译时知道将调用哪个方法。



代表特别用于实现事件和回调方法。


函数是常态。使用功能不起作用的代理,例如此处

We can perform same thing using delegate and function. So Where will we use delegate and where will we use function.

Roughly speaking a delegate is like a function pointer, that is a way to indirectly call a method.
As an example, see my solution to another question: "how to call multiple methods using loop, please help"[^].
More details, for instance, here: oop - Where do I use delegates? - Stack Overflow[^].


The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

Delegates are especially used for implementing events and the call-back methods.


A function is the norm. Use delegates where a function doesn't work, like here.