C#:INotifyPropertyChanged“模式”:为什么需要在引发事件之前检查事件
可能的重复:
为什么 C# 要求您在每次触发事件时编写空检查?
我经常看到以下代码,但不知为何不明白。
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("UIState"));
为什么我需要在引发事件之前检查事件是否为空。一直以来,至少当我尝试时,我只要提出事件就可以逃脱惩罚。
Possible Duplicate:
Why does C# require you to write a null check every time you fire an event?
I see often the following code but somehow don't get it.
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("UIState"));
Why do i need to check if the event is null before rasing it. All of the time, at least when I try it, I can get away with just raising the event.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它与 INotifyPropertyChanged 无关。任何未注册事件处理程序的事件都可以为 null,如果您尝试在该事件为 null 时调用 PropertyChanged(或任何事件),您将收到 NullReferenceException。
无法保证 PropertyChanged 永远不会为 null。碰巧的是,您总是在注册事件处理程序时调用它。
It has nothing to do with INotifyPropertyChanged. Any event that has no event handlers registered can be null, and if you try to call PropertyChanged (or any event) when it is null you will get a NullReferenceException.
There is no guarantee that PropertyChanged will never be null. It just so happens that you've always called it when an event handler was registered.