2012-10-11 17 views
2

可能重複:
Nullable types and the ternary operator: why is `? 10 : null` forbidden?根據案件如果子句用「:」

我希望分配一個值或空值至x(這是一個可爲空的整數) (你可以看到下面)

int? x; 
x = stackoverflow.ToString() != "" ? int.Parse(stackoverflow.ToString()) : null; 

但它給出了下面的錯誤。

Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '<null>' 

爲什麼?

+0

爲什麼int? X; ? – JonathanRomer

回答

4

將int轉換爲可爲null的int。

x = stackoverflow.ToString() != "" ? 
     (int?)int.Parse(stackoverflow.ToString()) : null; 
1

試試這個:

x = stackoverflow.ToString() != "" ? int.Parse(stackoverflow.ToString()) : (int?) null; 

,看看是否可行。我沒有測試它,因爲我不知道stackoverflow應該是