为什么 C# 要求您每次触发事件时都编写空检查?

Why does C# require you to write a null check every time you fire an event?(为什么 C# 要求您每次触发事件时都编写空检查?)
本文介绍了为什么 C# 要求您每次触发事件时都编写空检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

ActiveDirectory error 0x8000500c when traversing properties(遍历属性时 ActiveDirectory 错误 0x8000500c)
search by samaccountname with wildcards(使用通配符按 samaccountname 搜索)
Get the list of Groups for the given UserPrincipal(获取给定 UserPrincipal 的组列表)
Can you find an Active Directory User#39;s Primary Group in C#?(你能在 C# 中找到 Active Directory 用户的主要组吗?)
Query From LDAP for User Groups(从 LDAP 查询用户组)
How can I get DOMAINUSER from an AD DirectoryEntry?(如何从 AD DirectoryEntry 获取 DOMAINUSER?)