这对我来说似乎很奇怪——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# 要求您每次触发事件时都编写空检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!