【问题标题】:How to translate event driven code?如何翻译事件驱动的代码?
【发布时间】:2018-02-25 16:48:21
【问题描述】:

我主要是 C# 开发人员,最近正在开发一些 Android 项目。我必须在 Android 中实现一些自定义的书面事件,但我不知道该怎么做。 我为我想做的事情写了一个 C# 代码,所以如果有人能帮我把它翻译成 Android 代码,那将不胜感激。

我需要有一个自定义函数(事件),放在 MySecondClass 中,可以从 MyFirstClass 触发。 例如,我们有这个类:

private class MyFirstClass
{
    private event EventHandler<MyCustomEventArgs> _myCustomEvent;
    public event EventHandler<MyCustomEventArgs> MyCustomEvent
    {
        add { _myCustomEvent += value; }
        remove { _myCustomEvent -= value; }
    }

    public void Initialize()
    {
        MySecondClass myObjectSecondClass = new MySecondClass();
        this.MyCustomEvent += myObjectSecondClass.SomeMethodSecondClass;
    }

    public void SomeMethodFirstClass(int index)
    {
        //here we will trigger the event with some custom values
        EventsHelper.Fire(this.MyCustomEvent, this, new MyCustomEventArgs(index));
    }
}

MyCustomEventArgs 定义为:

public class MyCustomEventArgs : EventArgs
{
    public int index;

    public MyCustomEventArgs(int indexVal)
    {
        index = indexVal;
    }
}

而第二类定义为:

private class MySecondClass
{
    public void SomeMethodSecondClass(object sender, MyCustomEventArgs e)
    {
        //body of the method
        //we can use e.index here in the calculations
    }
}

所以我不确定如何在 Android 中处理这些“事件”相关的推荐。

【问题讨论】:

  • 你看过 xamarin 吗?

标签: android event-handling android-handler android-event event-triggers


【解决方案1】:

它在java中的所有接口。这里没有花哨复杂的关键字:)

应该有第二个类实现的接口。

public interface EventHandler{
     void onEventFired(EventParams e);
}

public class MyFirstClass{
     EventHandler eventHandler;

     public void initialize(){
         eventHandler = new MySecondClass();
     }

     public void method(){
         EventParams eventParams = new EventParams();
         //fire event here
         eventHandler.onEventFired(eventParams);
     }
}

public class MySecondClass implements EventHandler{
    @Overrride
    void onEventFired(EventParams e){
        //handle event here
    }
}

希望你能理解

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多