开发者

C#: INotifyPropertyChanged "pattern": Why need to check event before raising it [duplicate]

This question already has answers here: 开发者_JS百科 Closed 12 years ago.

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜