为什么 C# 要求您每次触发事件时都编写空检查?
- 作者: 来_来_这狗让你先日
- 来源: 51数据库
- 2022-10-20
问题描述
这对我来说似乎很奇怪——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#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
