在我的应用程序中,我有简单的 EventHandler (在我的 ViewModel 中)定义如下:
public event EventHandler FavouriteChangedEvent;
然后当我需要时,我用这个触发事件
FavouriteChangedEvent(this, null);
一切都按预期工作,但是在我的应用程序中,有可单击的链接,可以打开网络浏览器(作为单独的应用程序)。当您返回到应用程序时,当我尝试运行 FavouriteChangedEvent(this, null);
时,它会以 NullPointerException 结束(从调试来看,这是因为 FavouriteChangedEvent
确实为 null) .
这是为什么?
我在互联网上找到了这个并使用它
public delegate void EventHandler(object sender, string myValue);
public event EventHandler FavouriteChangedEvent = delegate { };
但这并没有多大帮助。应用程序不会下降,但在我的 View 类中,我在构造函数 _dataContext.FavouriteChangedEvent += _dataContext_FavouriteChangedEvent;
退出并返回应用后,不再触发该事件。
最佳答案
Then when I need, I fire the event with this
FavouriteChangedEvent(this, null);
it ends with NullPointerException (From debugging it is beacause FavouriteChangedEvent is really null
这是因为还没有事件处理程序。
event
是一个类
Once a class has declared an event, it can treat that event just like a field of the indicated delegate type. The field will either be null, if no client has hooked up a delegate to the event, or else it refers to a delegate that should be called when the event is invoked. Thus, invoking an event is generally done by first checking for null and then calling the event.
在上升事件之前,您至少必须检查 null
:
if(FavouriteChangedEvent != null)
FavouriteChangedEvent(this, null);
注意,要使此线程安全,您必须将事件复制到局部变量,以确保同一事件发生 null
检查和上升:
var event = FavouriteChangedEvent;
if(event != null)
event(this, null);
所描述的解决方案(在构造时附加空委托(delegate))是另一种可能的线程安全解决方案。
DO use a protected virtual method to raise each event
这就是说 - 不要像这样引发事件处理程序,而是调用 protected 虚拟方法(称为 OnFavouriteChangedEvent
)来引发事件。并且事件名称中不需要包含“事件”一词。让它变得简单:FavouriteChanged
。
关于c# - Wp8 - 从应用程序重定向并返回时,EventHandler 为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31156209/