2010-12-14 39 views
3

我一直拉着我的頭髮從一些意想不到的行爲可空整數。設置可空整數爲字符串包含什麼都沒有收益0

  • 如果我設置一個IntegerNothing,它成爲Nothing預期。
  • 如果我將Integer?設置爲StringNothing,它將變爲0!

當然,無論我是否明確地將String轉換成Integer?或不是,我都會得到這個結果。

我意識到我可以很容易地解決這個問題,但我想知道我錯過了什麼。

Dim NullString As String = Nothing 
    Dim NullableInt As Integer? = CType(NullString, Integer?) 'Expected NullableInt to be Nothing, but it's 0! 
    NullableInt = Nothing 'This works, of course. NullableInt is Nothing. 

編輯:以前我有我的代碼在這裏沒有這樣的明確轉變爲Integer?,每個人都似乎上被固定/通過混淆。有很多建議Option Strict On會捕獲這種類型的東西。然而,這實際上是一個字符串到整數轉換規則的怪癖,它早於可空類型,但仍然會影響它們。

+1

使用Option Strict On可以及早發現這些錯誤。 – 2010-12-14 17:29:31

+0

爲什麼要將一個字符串變量賦值給可空INteger?同意開啓選項嚴格打開 – 2010-12-14 21:44:58

+0

通過放置選項嚴格打開,您可以一次打開選項嚴格的一個文件。這應該讓你在處理文件時處理錯誤。從長遠來看,這絕對是值得的努力 – 2010-12-15 05:37:28

回答

6

這裏的原因與VB.Net轉換規則有關。 String類型與Integer?不兼容,因此發生轉換。儘管中間步驟是將String轉換爲Integer。所述VB.Net轉換規則將轉換Nothing或空StringInteger值0。這可以在不nullables

Dim local1 As String = Nothing 
Dim local2 As Integer = local1 ' It's 0 

再現此相同的轉換將則Integer值0轉換成其保持Integer類型Integer?值。

+0

+1:哇,所以我真的必須爲此編寫自己的小轉換?這似乎是軟醬。 – 2010-12-14 17:17:44

+0

@Brian MacKay:我會爭辯說,將空字符串'「」'解釋爲'Nullable(Of Integer)'沒有任何價值是非常具體的定製邏輯,並且您*必須*必須編寫自己的轉換,如果這是你想要的行爲(好消息是這很容易!)。只是我的兩分錢。 – 2010-12-14 17:29:25

+0

@丹濤:但字符串不是String.Empty,它是空的。 – 2010-12-14 21:23:16

0

爲什麼你想分配一個字符串到一個整數?

Dim nullInt As Nullable(Of Integer) 'nullInt = Nothing as expected 

    'the following should NOT compile and won't with Option Strict On 

    nullInt = "" 
    nullInt = String.Empty 
相關問題