简体   繁体   中英

xamarin EventHandler is always null

I have a code which should notify a delegate in one of service classes on receiving an event:

    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");
            }
        }
    }

I instantiate it by:

    private TestClass mytest= new TestClass ();

And then assign it in one of the functions:

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

The delegate never gets called. I have stepped through with debugger and I see that delegate is being assigned, but the check inside a class is always null... Cant figure out whats the problem...

Sounds like an execution order issue. What could be happening is that OnAction within TestClass is being called before the delegate hookup. Try the following:

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");
        }
    }
}

Just pass the delegate through the constructor, this should make sure its hooked up before any calls to OnAction()

You can pass through the handler in a couple ways:

1.) As an anonymous method:

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

2.) Pass in the method group:

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

private TestClass mytest= new TestClass(MyEventHandler);

I generally recommend the second way as it allows you to unhook the handler and do clean up once you are done with it:

myTest.MyDelegate -= MyEventHandler;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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