直接调用函数和通过委托调用之间的区别 [英] Difference between calling function directly and calling through delegate

查看:356
本文介绍了直接调用函数和通过委托调用之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨开发者,



任何人都可以清楚我的疑问,直接调用函数和

调用之间有什么区别(调用)函数通过委托



使用委托来调用函数有什么好处?



提前谢谢。

解决方案

优点是你不必在编译时知道事件的名称 - 你可以打电话在运行时匹配签名的任何方法。



例如,如果您编写一种方法来打印使用Write委托的发票,那么可以提供方法使用Write方法打印到TextBox,另一个打印到文件,第三个打印到控制台,第四个打印到打印机,依此类推,根本不改变原始方法 - 它不必知道数据正在进行中,它只依赖于您在向代理提供的每种方法中执行与数据相关的操作。这意味着该方法可以很好,干净,无需任何更改即可添加到输出列表。



还有许多其他用途,但它们都干从这个基本前提。


与函数指针一样,您可以在运行时更改委托,请参阅文档 [ ^ ]。


使用代表的优势:



1.它提供了一种方法来封装你的方法。



2.它解决了你的<之间非常紧密耦合的问题b>业务逻辑代码和用户界面 UI 。意味着无论何时更改业务逻辑代码(添加/编辑/删除任何方法),您都必须相应地更改 UI 代码。但是通过使用委托,您的 UI 代码将指向一个抽象指针,并将访问该业务逻辑代码。因此, UI 无需了解业务逻辑代码。



希望它有所帮助:)

Hi Developers,

Can any one clear my doubt, What is the difference between calling the function directly and
calling(invoking) the function through delegate,

what are the advantages of using delegate to call function ?

Thanks in advance.

解决方案

The advantage is that you don't have to know the name of the event at compile time - you can call any method which matches the signature at run time.

For example, if you write a method to print an invoice which uses a Write delegate, then to can supply the method with a Write method to print to a TextBox, another to print to a file, a third to the Console, a fourth to the printer, and so on, without changing the original method at all - it doesn't have to know where the data is going, it just relies on you doing something relevant with the data in every method you supply to the delegate. This means that the method can be nice and clean, without any changes needed to add to the list of outputs.

There are loads of other uses, but they all stem from this basic premise.


Like function pointers, you may change the delegate at runtime, see the documentation[^].


The advantage of using delegates:

1. It provides a way to encapsulate your methods.

2. It solves the problem of very tight coupling between your business logic code and User Interface UI. Means whenever you changes to your business logic code(add/Edit/delete any method) you have to change the UI code as well accordingly. But by using delegates your UI code will point to an abstract pointer and that will access that business logic code. Hence the UI need not to know about the business logic code.

hope it helps :)


这篇关于直接调用函数和通过委托调用之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆