解釋爲什麼一個可空INT不能被賦值爲null e.g的價值C#爲什麼不能爲null的INT被賦值爲null作爲值
int? accom = (accomStr == "noval" ? null : Convert.ToInt32(accomStr));
什麼是錯的代碼?
解釋爲什麼一個可空INT不能被賦值爲null e.g的價值C#爲什麼不能爲null的INT被賦值爲null作爲值
int? accom = (accomStr == "noval" ? null : Convert.ToInt32(accomStr));
什麼是錯的代碼?
問題不在於null無法分配給int ?.問題是三元運算符返回的兩個值必須是相同的類型,否則必須隱式轉換爲另一個。在這種情況下,null不能隱式地轉換爲int,也不能使用,因此必須使用explict轉換。試試這個:
int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr));
哈里說什麼是完全正確的,但
int? accom = (accomStr == "noval" ? null : (int?)Convert.ToInt32(accomStr));
也將這樣的伎倆。 (我們ReSharper的用戶可隨時抽查彼此在人羣中...)
另一種選擇是使用
int? accom = (accomStr == "noval" ? Convert.DBNull : Convert.ToInt32(accomStr);
我喜歡這一張最。
同樣我也爲長:
myLongVariable = (!string.IsNullOrEmpty(cbLong.SelectedItem.Value)) ? Convert.ToInt64(cbLong.SelectedItem.Value) : (long?)null;
這很有趣 - 你實際上並不需要的塑像爲Convert.ToInt32 ... – 2008-12-01 10:44:38
這是因爲System.Int32 = System.Nullable –
2008-12-01 10:59:58
爲什麼長! ?工作沒有演員? – 2010-05-27 13:49:07