问题描述
什么是 C#
中的事件?你可以给我一个清晰的实时示例和程序吗?
What are events in C#
? Can you give me a clear real time example and program?
推荐答案
事件是一个对象上的钩子,对象可以说嘿,有趣的事情即将发生(或刚刚发生),对象外部的代码可以说(在此之前发生),我对该消息感兴趣。
An event is a hook on an object where the object can say "Hey, something interesting is about to happen" (or just happened), and code on the outside of the object can say (before that something happens) that "I'm interested in that message".
以按钮为例,此代码:
btOK.Click += new EventHandler(btOK_Click);
这对按钮说:嘿,当你想点击Click事件用户点击按钮),通过调用我的方法btOK_Click让我知道。
This says to the button: Hey, when you want to fire the Click event (which is fired when the user clicks on the button), let me know by calling my method, btOK_Click.
你可以想到另一种方式。假设你的显示器附有一个黄色的贴纸笔记,说每当代码停止编译,请致电Frank,这是一个事件。当你打电话给他的时候,弗兰克做了什么,那就是事件处理者,这个代码是为了回应你的事情而运行的。
You can think of it another way. Let's say that you have a yellow postit note attached to your monitor that says "Whenever the code stops compiling, please call Frank", that's an event. What Frank does when you call him, that's the "Event Handler", the "code" that runs in response to your event.
所以这些术语是:
- 事件:一个对象上的钩子,对象的外部代码可以说什么事情 - 发生这种事情的时候,可以打电话给我代码
- 事件处理程序:事件触发时调用的代码
- 启动事件:基本上与调用一样,它只是一个不同的单词本质上是一样的东西
有很多关于事件和.NET / C#的信息:
There's plenty of information on the web about events and .NET/C#:
- MSDN: Events Tutorial
- C# Help: C# Events
- Devhood: Introduction to C# Events
- C#-Station: Introduction to delegates and events
或者您可以在这里询问更具体的问题,确定有人会帮助您了解细节。
or... you can just ask more specific questions here, and I'm sure somebody will help you understand the details.
快乐的事件处理。
这篇关于C#中的事件 - 定义和示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!