日期:2014-05-18  浏览次数:20450 次

EventHandler和EventArgs 分别是什么意思
如题 ,这两天弄一下事件机制,但是看了点别人得代码 这两个如何应用没太弄没白。希望高手给点实例。

------解决方案--------------------
前者是一个委托,代表事件处理函数的参数和返回值类型。
后者是一个类,作为事件参数传递给事件处理函数。
------解决方案--------------------
EventHandler 是一个委托;事件处理函数的参数和返回值类型
EventArgs 是一个类;事件的参数
------解决方案--------------------
public delegate MyEventHandler;
public MyEventArgs:EventArgs {....}
XXX.MyEvent+=new MyEventHandler(MyEvent_Click)
MyEvent_Click(object sender,MyEventArgs e)
{.....}
.....etc
------解决方案--------------------
C# code
//A.cs
class A
{
    public delegate void EventHandler(object sender, EventArgs e);
    public event EventHandler AEvent;
    public foo()
    {
        AEvent(this, new EventArgs());
    }
}

//Program.cs
static void Main(string[] Args)
{
    A a = new A();
    a.AEvent += new A.EventHandler(On_AEvent);
    a.foo();
}

static void On_AEvent(object sender, EventArgs e)
{
    Console.WriteLine("On_AEvent");
}

------解决方案--------------------
C# code
//A.cs
class A
{
    public delegate void EventHandler(object sender, EventArgs e);
    public event EventHandler AEvent;
    public void foo()
    {
        AEvent(this, new EventArgs());
    }
}

//Program.cs
static void Main(string[] Args)
{
    A a = new A();
    a.AEvent += new A.EventHandler(On_AEvent);
    a.foo();
}

static void On_AEvent(object sender, EventArgs e)
{
    Console.WriteLine("On_AEvent");
}