使用myevent(this,EventArgs.Empty)的目的是什么?

本文关键字:是什么 Empty EventArgs myevent this 使用 | 更新日期: 2023-09-27 18:10:23

我目前正在学习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);
 }

这些行的目的是什么?

使用myevent(this,EventArgs.Empty)的目的是什么?

这段代码引发了事件。如果事件未引发,则不执行事件处理程序。

一个委托是一个对象,它引用一个方法,一个事件有点像委托的集合。如果您不向事件添加任何处理程序,则没有收集,因此检查null。如果事件不是null,则意味着已经注册了处理程序。if语句内的行引发事件,这意味着调用集合中的每个委托。当每个委托被调用时,它所引用的方法被执行。被执行的方法是您的事件处理程序。

EventArgs:EventArgs是该事件的实现者可能会发现有用的参数。与OnClick它不包含什么好,但在一些事件,比如在GridView 'SelectedIndexChanged',它将包含新的索引,或一些其他有用的数据。

EventArgs。空:用于将值传递给与没有数据的事件相关联的事件处理程序。

您的事件类型为mydel

public mydel myevent;//使用签名void mydel()声明mydel类型的事件

希望这能给你一些火花。

   if (myevent != null) //Checks so you instantiated a event
   { 
        myevent(this,EventArgs.Empty); // {this} will be equal to the sender in delegete myDel, {EventArgs.Empty} is since you are not passing any arguments to your delegate. 
   }