我们什么时候应用C# [英] When should we use event in C#

查看:144
本文介绍了我们什么时候应用C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#和WPF的新手。而我刚刚在C#中学到了异步编程。
我们提出事件,一些我们捕获这个事件的地方。



这种方法的优点是我们不需要直接调用对象方法。例如,我们从数据库加载数据,然后在加载数据方法完成后,它会引发事件 LoadDataSuccessfully
然后主类捕获此事件并引发事件 UpdateGUIAfterLoadDataSuccessfully ,其他一些控件将捕获此事件并更新GUI。



但现在我认为可能...我用它在我的项目中太多了,可能我过度使用了。
请给我一些建议,当我们应该使用Event,何时应该采用传统的方式。

解决方案

事件应该使用这些代码,这些代码起源于对该操作作出反应的代码的直接知识。



让我们帮助解释的例子



问题



在您的系统中,将数据对象发送给您说你有一个从外部系统每分钟发送的50个数据对象。接收到这个数据对象后,你需要让它被另一个对象处理。



一个事件或一个简单的方法调用更好地在这种情况下使用?



答案



一方面,事件在这里听起来很合适,因为处理数据接收的代码不应该依赖于执行与所述数据有关的代码的实现。否则,数据接收代码现在负责两件事情 - 接收数据的处理。



另一方面,如果数据的特定处理与外部呼叫者发送的行为直接相关,可能会使其成为函数调用更有意义。 b

查看


I am a newbie of C# and WPF. And I just learned the asynchronous programming in C#. We raise event and some where we catch this event.

The advantage of this method is we don't need to call directly the object method. Example we load data from database, then after load data method is finish, it raise the event LoadDataSuccessfully Then the main class catch this event and raise event UpdateGUIAfterLoadDataSuccessfully, some other Control will catch this event and update GUI.

But now I think may be... I use it too much in my project, may be i overuse it too much. Please give me some advices, when we should use Event and when we should do the traditional way.

解决方案

Events should be used when it is inappropriate for the code which originates the action to have direct knowledge of the code(s) which react to that action.

Lets explain with an help of example

Question

In your System you have Data objects sent to you say you have 50 Data object sent per minute from an external system.Upon receiving this you need to have it processed by another object.

Would an event or a simple method call be better to use in this situation?

Answer

On one hand, an event does sound appropriate here, because the code which handles data reception should not be dependent on the implementation of the code which does something with said data. Otherwise the data reception code is now responsible for two things - receiving the data and delegating the processing of it.

On the other hand, if the particular processing of the data is directly tied to act of it being sent by the external caller, it may make more sense to make it a function call

Take a look at this

这篇关于我们什么时候应用C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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