C# 事件处理(与 Java 相比) [英] C# event handling (compared to Java)

查看:16
本文介绍了C# 事件处理(与 Java 相比)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前很难理解和使用 delegates 在 C# 中实现事件.我习惯了Java的做事方式:

  1. 为包含许多方法定义的侦听器类型定义一个接口
  2. 如果我对侦听器中定义的所有事件不感兴趣,请为该接口定义适配器类以使事情变得更容易
  3. 在引发事件的类中定义 Add、Remove 和 Get[] 方法
  4. 定义受保护的触发方法来完成循环添加的侦听器列表并调用正确方法的繁琐工作

我理解(并且喜欢!) - 我知道我可以在 c# 中完全一样地做到这一点,但似乎为 c# 准备了一个新的(更好的?)系统.在阅读了无数解释 c# 中委托和事件使用的教程之后,我仍然没有更接近真正理解发生了什么:S

<小时>

简而言之,对于以下方法,我将如何在 c# 中实现事件系统:

void computerStarted(计算机);void computerStopped(计算机);无效计算机重置(计算机);void computerError(计算机,异常错误);

^ 以上方法取自我曾经制作的一个 Java 应用程序,我正试图将其移植到 c#.

非常感谢!

解决方案

您将创建四个事件和引发它们的方法,以及一个新的基于 EventArgs 的类来指示错误:

公共类 ExceptionEventArgs : EventArgs{私有只读异常错误;公共 ExceptionEventArgs(异常错误){this.error = 错误;}公共错误{获取{返回错误;}}}公共课电脑{公共事件 EventHandler 开始 = 委托{};公共事件 EventHandler 停止 = 委托{};公共事件 EventHandler 重置 = 委托{};公共事件EventHandler<ExceptionEventArgs>错误 = 委托{};受保护的无效 OnStarted(){开始(这个,EventArgs.Empty);}受保护的无效 OnStopped(){停止(这个,EventArgs.Empty);}受保护的无效 OnReset(){重置(这个,EventArgs.Empty);}受保护的无效 OnError(异常 e){错误(这个,新的异常事件参数(e));}}

然后类将使用方法或匿名函数订阅事件:

someComputer.Started += StartEventHandler;//一个方法someComputer.Stopped += delegate(object o, EventArgs e){Console.WriteLine("{0} 已启动", o);};someComputer.Reset += (o, e) =>Console.WriteLine("{0} 已被重置");

以上几点需要注意:

  • OnXXX 方法受到保护,因此派生类可以引发事件.这并不总是必要的 - 做你认为合适的事情.
  • 每个事件声明中的 delegate{} 部分只是避免进行空值检查的技巧.它为每个事件订阅了一个无操作事件处理程序
  • 事件声明是类字段事件.实际创建的是一个变量一个事件.在类中,您会看到变量;在课堂之外,您会看到活动.

请参阅我的 events/delegates 文章,了解有关事件的更多详细信息.p>

I am currently having a hardtime understanding and implementing events in C# using delagates. I am used to the Java way of doing things:

  1. Define an interface for a listener type which would contain a number of method definitions
  2. Define adapter class for that interface to make things easier if I'm not interested in all the events defined in a listener
  3. Define Add, Remove and Get[] methods in the class which raises the events
  4. Define protected fire methods to do the dirty work of looping through the list of added listeners and calling the correct method

This I understand (and like!) - I know I could do this exactly the same in c#, but it seems that a new (better?) system is in place for c#. After reading countless tutorials explaining the use of delegates and events in c# I still am no closer to really understanding what is going on :S


In short, for the following methods how would I implement the event system in c#:

void computerStarted(Computer computer);
void computerStopped(Computer computer);
void computerReset(Computer computer);
void computerError(Computer computer, Exception error);

^ The above methods are taken from a Java application I once made which I'm trying to port over to c#.

Many many thanks!

解决方案

You'd create four events, and methods to raise them, along with a new EventArgs-based class to indicate the error:

public class ExceptionEventArgs : EventArgs
{
    private readonly Exception error;

    public ExceptionEventArgs(Exception error)
    {
         this.error = error;
    }

    public Error
    {
         get { return error; }
    }
}

public class Computer
{
    public event EventHandler Started = delegate{};
    public event EventHandler Stopped = delegate{};
    public event EventHandler Reset = delegate{};
    public event EventHandler<ExceptionEventArgs> Error = delegate{};

    protected void OnStarted()
    {
        Started(this, EventArgs.Empty);
    }

    protected void OnStopped()
    {
        Stopped(this, EventArgs.Empty);
    }

    protected void OnReset()
    {
        Reset(this, EventArgs.Empty);
    }

    protected void OnError(Exception e)
    {
        Error(this, new ExceptionEventArgs(e));
    }
}

Classes would then subscribe to the event using either a method or a an anonymous function:

someComputer.Started += StartEventHandler; // A method
someComputer.Stopped += delegate(object o, EventArgs e)
{ 
    Console.WriteLine("{0} has started", o);
};
someComputer.Reset += (o, e) => Console.WriteLine("{0} has been reset");

A few things to note about the above:

  • The OnXXX methods are protected so that derived classes can raise the events. This isn't always necessary - do it as you see fit.
  • The delegate{} piece on each event declaration is just a trick to avoid having to do a null check. It's subscribing a no-op event handler to each event
  • The event declarations are field-like events. What's actually being created is both a variable and an event. Inside the class you see the variable; outside the class you see the event.

See my events/delegates article for much more detail on events.

这篇关于C# 事件处理(与 Java 相比)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆