2015-11-16 97 views
0

我有一个代码,应在服务类中的一个在接收到一个事件通知委托:xamarin事件处理程序总是空

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) => { 
    }; 

委托不会被调用。我已经通过调试程序,我看到代理正在分配,但类内的检查总是空的...不知道怎么回事...

+0

怎么样给它分配在构造 - 机会是你的执行顺序是不正确的 –

+0

@StenPetrov哦..你的意思是如果我做了一个任务后创建一个对象,它不会工作? – Ulterior

+0

在你的'mytest.MyDelegate + = ...'和'OnAction'里面放置一个断点 - 看看先被命中了什么 –

回答

1

听起来像一个执行顺序问题。可能发生的情况是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()

任何电话,您可以在几个方面通过处理程序之前迷上了:

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; 
+0

如何实例化一个EventHandler将其传递给构造函数? – Ulterior

+0

更新了答案 – pnavk