2017-07-11 124 views
-7

我有這個條件空條件運算符是否返回false如果爲空?

if (item?.Value2?.GetType() != typeof(string) && item.get_Value() == 0)

我相信,如果項目是空的?.操作將返回null,我相信會被解析爲false導致病情短路和一切都會好起來(item.get_Value()將不會被調用)

但是我不能肯定,我想也許我需要做的是,像這樣

if (item?.Value2?.GetType() ?? 0 != typeof(string) && item.get_Value() == 0)

但我認爲這可能是矯枉過正,是第一種安全的潛在空引用異常嗎?

+8

沒有必要對「信仰」的編程。你可以隨時啓動編譯器並測試它。 –

+0

是一個單元格Excel範圍項目?你想檢查單元格值是否爲0或顯示的格式文本是否爲「0」?這是矯枉過正,缺少很多邊緣案例。 – Slai

+4

爲什麼不只是1. [閱讀文檔](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators)和/或2.嘗試一下親眼看看? –

回答

5

item?.Value2?.GetType()將返回null如果itemnullValue2null

評價將是

if (null != typeof(string) && item.get_Value() == 0) 

所以第一個條件將被解析成true引起的病症的NullReferenceExceptionitem.get_Value() == 0將被執行(但只有當itemnull,而不是Value2

+0

@RufusL'null!= typeof(string)'將評估爲'true' – Alberto

+0

@hellyale它取決於,'get_Value()'的返回值是什麼? – Alberto

+0

@hellyale如果'item'爲null,那麼'item?.get_value()'將返回null,並且表達式'item?.get_Value()== 0'將被賦值爲'false' – Alberto

1

.Value2速度更快,但對於格式爲日期或貨幣的單元格,.Value2返回Double,但.Value.get_Value()返回DateTim e和小數。如果單元格是數字類型,則兩者都會導致Double;如果值不是數字類型或數字格式爲文本,則兩者都會導致String。返回類型也可以爲布爾值爲TRUE和FALSE,整數爲錯誤。


if (0.0.Equals(item.Value2)) // if (item.Value2 is Double && (Double)(item.Value2) == 0.0) 

這可能看起來很奇怪,但它是檢查是否運行時type is Double and equal 0.0最短和最安全的方式。 (項不爲空,如果它是枚舉範圍的結果)


至於實際的問題,找到的第0細胞:

Range cell = range.Find(0, LookAt: XlLookAt.xlWhole); 
if (cell != null) { /* ... */ }