問題描述
這對我來說似乎很奇怪——VB.NET 通過它的 RaiseEvent
關鍵字隱式地處理空檢查.它似乎大大增加了圍繞事件的樣板數量,我看不出它提供了什么好處.
This seems odd to me -- VB.NET handles the null check implicitly via its RaiseEvent
keyword. It seems to raise the amount of boilerplate around events considerably and I don't see what benefit it provides.
我確信語言設計者有充分的理由這樣做..但我很好奇是否有人知道原因.
I'm sure the language designers had a good reason to do this.. but I'm curious if anyone knows why.
推薦答案
這當然是一個煩惱點.
當您編寫訪問類中類似字段的事件的代碼時,您實際上是在訪問該字段本身(以 C# 4 中的一些更改為模;我們暫時不去那里).
When you write code which accesses a field-like event within a class, you're actually accessing the field itself (modulo a few changes in C# 4; let's not go there for the moment).
所以,選項是:
- 特殊情況下的類似字段的事件調用,以便它們實際上并不直接引用該字段,而是添加了一個包裝器
以不同的方式處理所有委托調用,例如:
Action<string> x = null;
x();
不會拋出異常.
當然,對于非無效委托(和事件),這兩種選擇都會產生問題:
Of course, for non-void delegates (and events) both options raise a problem:
Func<int> x = null;
int y = x();
應該默默地返回0嗎?(int
的默認值.)或者它實際上掩蓋了一個錯誤(更有可能).讓它默默地忽略您試圖調用空委托的事實會有些不一致.在這種情況下會更奇怪,它不使用 C# 的語法糖:
Should that silently return 0? (The default value of an int
.) Or is it actually masking a bug (more likely). It would be somewhat inconsistent to make it silently ignore the fact that you're trying to invoke a null delegate. It would be even odder in this case, which doesn't use C#'s syntactic sugar:
Func<int> x = null;
int y = x.Invoke();
基本上,無論您做什么,事情都會變得棘手且與語言的其余部分不一致.我也不喜歡它,但我不確定一個實用但一致的解決方案可能是什么......
Basically things become tricky and inconsistent with the rest of the language almost whatever you do. I don't like it either, but I'm not sure what a practical but consistent solution might be...
這篇關于為什么 C# 要求您每次觸發事件時都編寫空檢查?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!