为什么C#要求你写你每次触发事件的时间空检查? [英] Why does C# require you to write a null check every time you fire an event?

查看:308
本文介绍了为什么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.

推荐答案

这当然烦恼的一个点。

当你写code它访问一个类中的一个字段般的事件,你的真正的访问字段本身(模在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).

所以,选项是:


  • 特殊情况下的现场般的事件调用,使他们实际上并没有指到外地直接,而是增加了一个包装

  • 拉手的所有的委托调用不同的选择,例如:

  • Special-case field-like event invocations so that they didn't actually refer to the field directly, but instead added a wrapper
  • Handle all delegate invocations differently, such that:

Action<string> x = null;
x();

不会抛出异常。

当然,对于非void代表(和事件)两个方案提出一个问题:

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#要求你写你每次触发事件的时间空检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆