我目前正在学习csharp中的委托和事件。我有以下代码集:
using System;
using System.Collections.Generic;
using System.Text;
public delegate void mydel(object sender, EventArgs e);
class event1
{
public event mydel myevent;
public void onfive()
{
Console.WriteLine("I am onfive event");
Console.ReadKey();
if (myevent != null)
{
myevent(this,EventArgs.Empty);
}
}
}
public class test
{
public static void Main()
{
event1 e1 = new event1();
e1.myevent += new mydel(fun1);
Random ran = new Random();
for (int i = 0; i < 10; i++)
{
int rn = ran.Next(6);
Console.WriteLine(rn);
Console.ReadKey();
if (rn == 5)
{
e1.onfive();
}
}
}
public static void fun1(object sender, EventArgs e)
{
Console.WriteLine(" i am surplus function called due to use of '+=' ");
Console.ReadKey();
}
}
每当我在注释中放入以下行时,就不会调用fun1()函数。为什么会这样?
if (myevent != null)
{
myevent(this,EventArgs.Empty);
}
这些线的目的是什么?
答案 0 :(得分:0)
EventArgs: EventArgs是此事件的实现者可能觉得有用的参数。使用OnClick它没有任何好处,但在某些事件中,比如在GridView&#39; SelectedIndexChanged&#39;中,它将包含新索引或一些其他有用数据。
EventArgs.Empty:用于将值传递给与没有数据的事件关联的事件处理程序。
您的活动类型为 mydel 。
public mydel myevent; //使用签名void mydel()
声明类型为mydel的事件希望这可能会给你一些启发。
答案 1 :(得分:0)
这段代码是引发事件的原因。如果未引发事件,则不执行事件处理程序。
委托是一个引用方法的对象,事件有点像委托集合。如果您没有向事件添加任何处理程序,则没有集合,因此检查null
。如果事件不是null
,那么这意味着处理程序已经注册。 if
语句中的行引发了事件,这意味着调用集合中的每个委托。在调用每个委托时,执行它所引用的方法。执行的方法是您的事件处理程序。