活动是代表,我需要一个小例子来了解所有内容 [英] Events are delegates, i need a small example to understand everything
本文介绍了活动是代表,我需要一个小例子来了解所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
能给我一个小例子,说明我们如何使用事件以及如何将委托一起使用,
在其中有EventHandler的地方,我们在其中引发事件并对其进行处理.
请给我一个小例子,并逐步说明.
我已经读了很多书,但是找不到一个很好的例子来理解一切工作原理.
Can you give me a small example how we used events, and delegates together,
something where there is EventHandler, where we raise the event and handle it.
Please give me a small example and explain it step by step.
I have read a lot, but cant find a good example to understand how everything works
推荐答案
我过去曾经问过这个问题.
阅读此 [
I asked this question once in the past.
Read this[^] question and solution 1!
Handler
是在Event
之后被调用的方法.
Delegate
是指向Handler
的点.
Delegate
指定Handler数据类型及其参数名称和参数数据类型.
Handler
is a method that is being called after theEvent
.
Delegate
is a point to theHandler
.
Delegate
specifies Handler data type and it''s parameters names and parameters data types.
public class Person
{
private static Random random = new Random();
private string[] words = new string[10] { "I am talking", "Good", "Oh!", "Wow!", "No.", "Bingo", "Wait a second", "I'm busy right now.", "LOL", "What?" };
public string Name { get; set; }
public void Say(Person addressee)
{
System.Threading.Thread.Sleep(500);
if(onSay!= null)
onSay(this, words[random.Next(0, 9)]);
addressee.Say(this);
}
public delegate void SayHandler(Person sender, string word);
public SayHandler onSay;
}
在简单控制台应用程序中进行测试:
For testing in a Simple Console Application:
class Program
{
static void Main(string[] args)
{
Person person1 = new Person()
{
Name = "John"
};
Person person2 = new Person()
{
Name = "Bill"
};
person1.onSay += new Person.SayHandler(SomeBodySay);//It determines that SomeBodySay method must be call after calling onSay method. For person1
person2.onSay += new Person.SayHandler(SomeBodySay);
person1.Say(person2);
Console.ReadKey();
}
static void SomeBodySay(Person person, string word)
{
Console.WriteLine("{0} said: {1}", person.Name, word);
}
而且这可能会有所帮助:
C#中的事件和事件处理 [
And also this may helps:
Events and event handling in C#[^]
这篇关于活动是代表,我需要一个小例子来了解所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文