繁体   English   中英

如何实现这种事件侦听器设计?

[英]How do I implement this kind of event listener design?

我是C#的新手,所以这可能只是我不了解该语言的某些基本知识或某些功能所缺少的知识。 我已经在线搜索过,但是我似乎找到的所有示例都将所有内容都放在一个类中(换句话说,它们定义了事件以及触发事件时执行的方法),这不是我想要的。

对于我的场景,我想定义一个侦听器方法的接口,该接口可以接受一些提供指令的自定义参数(这是我自己的EventArgs对吗?)。 让我们假装一辆汽车,所以我有一个名为:

  • 开始(MyCustomParameters参数)
  • 加速(MyCustomParameters参数)
  • 减速(MyCustomParameters参数)

然后我希望能够创建提供这些方法的实际实现的类。

与所有这些完全分离,我有一个基于外部过程定期执行的类,并且我希望它负责触发这些事件(当汽车起步和加速等时)。

这就是我要努力工作的基础,但到目前为止还没有运气。 此外,还有一个后续问题。 如果我的侦听器实现类需要维持给定调用的任何状态,则如何最好地做到这一点(例如,说当Accelerate被调用时,它希望能够将加速后的速度返回给该调用者。事件-例如80公里/小时)

希望您能提供帮助,非常感谢

这是c#中的事件/侦听器的简单示例:

 //your custom parameters class
    public class MyCustomParameters
    {
        //whatever you want here...
    }

    //the event trigger
    public class EventTrigger
    {
        //declaration of the delegate type
        public delegate void AccelerationDelegate(MyCustomParameters parameters);

        //declaration of the event
        public event AccelerationDelegate Accelerate;

        //the method you call to trigger the event
        private void OnAccelerate(MyCustomParameters parameters)
        {
            //actual triggering of the events
            if (Accelerate != null)
                Accelerate(parameters);
        }
    }

    //the listener
    public class Listener
    {
        public Listener(EventTrigger trigger)
        {
            //the long way to subscribe to the event (to understand you create a delegate)
            trigger.Accelerate += new EventTrigger.AccelerationDelegate(trigger_Accelerate);

            //a shorter way to subscribe to the event which is equivalent to the statement above
            trigger.Accelerate += trigger_Accelerate;
        }

        void trigger_Accelerate(MyCustomParameters parameters)
        {
            //implement event handling here
        }
    }

希望对您有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM