繁体   English   中英

xamarin EventHandler始终为null

[英]xamarin EventHandler is always null

我有一个代码,该代码应在接收事件时通知服务类之一中的委托:

    public class TestClass : ParentClass
    {
        public event EventHandler<string> MyDelegate;

        public override void OnAction(Context context, Intent intent)
        {
            var handler = MyDelegate;
            if (handler != null)
            {
                handler(this, "test");
            }
        }
    }

我通过以下方式实例化它:

    private TestClass mytest= new TestClass ();

然后将其分配给以下功能之一:

    mytest.MyDelegate+= (sender, info) => {
    };

代表永远不会被呼叫。 我已逐步调试程序,并看到已分配了委托,但是类内的检查始终为空...无法找出问题所在...

听起来像是执行订单问题。 可能发生的事情是在委托连接之前调用TestClass中的OnAction 请尝试以下操作:

public class TestClass : ParentClass
{
    public event EventHandler<string> MyDelegate;

    public class TestClass(Action<string> myAction)
    {
      MyDelegate += myAction;
    }

    public override void OnAction(Context context, Intent intent)
    {
        var handler = MyDelegate;
        if (handler != null)
        {
            handler(this, "test");
        }
    }
}

只需将委托传递给构造函数,就可以确保在调用OnAction()之前OnAction()其连接

您可以通过以下两种方式来传递处理程序:

1.)作为匿名方法:

private TestClass mytest= new TestClass ((sender, info) => { Console.WriteLine("Event Attached!") });

2.)传入方法组:

public class MyEventHandler(object sender, string e)
{
  Console.WriteLine("Event Attached!");
}

private TestClass mytest= new TestClass(MyEventHandler);

我通常推荐第二种方法,因为它可以让您解开处理程序并在完成处理后进行清理:

myTest.MyDelegate -= MyEventHandler;

暂无
暂无

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

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