久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

為什么 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# 要求您每次觸發事件時都編寫空檢查?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

Why shouldn#39;t I always use nullable types in C#(為什么我不應該總是在 C# 中使用可空類型)
C# HasValue vs !=null(C# HasValue vs !=null)
C# ADO.NET: nulls and DbNull -- is there more efficient syntax?(C# ADO.NET:空值和 DbNull —— 有沒有更高效的語法?)
How to set null value to int in c#?(如何在c#中將空值設置為int?)
How to handle nulls in LINQ when using Min or Max?(使用 Min 或 Max 時如何處理 LINQ 中的空值?)
Method call if not null in C#(在 C# 中如果不為 null 的方法調用)
主站蜘蛛池模板: 日韩精品色网 | 97伦理电影网 | 九九九精品视频 | 亚洲欧美日韩久久久 | 亚洲视频一区二区三区 | 欧美性网 | 国产日韩欧美一区二区 | 国产成人99久久亚洲综合精品 | 欧美一区二区二区 | 国产 日韩 欧美 在线 | 日韩欧美在线视频观看 | 久久久www| av入口| 国产综合精品一区二区三区 | 成人精品毛片 | 欧美激情一区二区三级高清视频 | 欧美美女二区 | 久久久一区二区三区四区 | 成人免费观看网站 | 毛片久久久 | 欧美福利一区 | 久久33| 日韩在线中文 | 国产成人精品久久 | 免费在线观看av片 | 欧美国产日韩在线观看 | 激情黄色在线观看 | 精品国产乱码久久久久久蜜柚 | 精品国产一区二区三区在线观看 | 国产真实精品久久二三区 | 亚洲视频三 | 蜜桃黄网 | 国产高清视频一区 | 日韩精品免费看 | 97精品国产97久久久久久免费 | 精品伊人久久 | 国产1页 | 久草精品视频 | 日韩精品999| 97精品国产一区二区三区 | 国产农村妇女毛片精品久久麻豆 |