2008-12-01 62 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; 
相关问题