2008-12-01 61 views

回答

207

問題不在於null無法分配給int ?.問題是三元運算符返回的兩個值必須是相同的類型,否則必須隱式轉換爲另一個。在這種情況下,null不能隱式地轉換爲int,也不能使用,因此必須使用explict轉換。試試這個:

int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr)); 
+3

這很有趣 - 你實際上並不需要的塑像爲Convert.ToInt32 ... – 2008-12-01 10:44:38

+1

這是因爲System.Int32 = System.Nullable 2008-12-01 10:59:58

+1

爲什麼長! ?工作沒有演員? – 2010-05-27 13:49:07

36

哈里說什麼是完全正確的,但

int? accom = (accomStr == "noval" ? null : (int?)Convert.ToInt32(accomStr)); 

也將這樣的伎倆。 (我們ReSharper的用戶可隨時抽查彼此在人羣中...)

5

另一種選擇是使用

int? accom = (accomStr == "noval" ? Convert.DBNull : Convert.ToInt32(accomStr); 

我喜歡這一張最。

1

同樣我也爲長:

myLongVariable = (!string.IsNullOrEmpty(cbLong.SelectedItem.Value)) ? Convert.ToInt64(cbLong.SelectedItem.Value) : (long?)null; 
相關問題