2013-02-26 127 views
1

出於某種原因,Visual Studio中有這一行的一個問題:Convert.ToInt32適用於if語句,但不適用於?運營商

MandatoryStakeholder.SupportDocTypeID = (String.IsNullOrEmpty(allIDValues[1]) || (allIDValues[1] == "0")) ? null : Convert.ToInt32(allIDValues[1]); 

具體的Convert.ToInt32(allIDValues[1])部分。錯誤是「C#:這些類型是不兼容‘空’:‘詮釋’」

但是如果我模仿的是邏輯與它下面有沒有問題:

if (string.IsNullOrEmpty(allIDValues[1]) || Convert.ToInt32(allIDValues[1]) == 0) 
       stakeHolder.SupportDocTypeId = null; 
      else 
       stakeHolder.SupportDocTypeId = Convert.ToInt32(allIDValues[1]); 

MandatoryStakeholder.SupportDocTypeID是int類型的? 。不知道爲什麼我可以在if語句中將字符串轉換爲int類型,但不能與?運營商。

+1

我相信三元應該在兩個分支中具有相同的返回類型。所以你需要一個'int'而不是'null'。 – FlyingStreudel 2013-02-26 20:55:51

回答

3

嘗試鑄造nullint?

MandatoryStakeholder.SupportDocTypeID = 
    (String.IsNullOrEmpty(allIDValues[1]) || (allIDValues[1] == "0")) ? 
     (int?)null : 
     Convert.ToInt32(allIDValues[1]); 
3

? null更改爲? (int?) null

MandatoryStakeholder.SupportDocTypeID = (String.IsNullOrEmpty(allIDValues[1]) || (allIDValues[1] == "0")) ? (int?)null : Convert.ToInt32(allIDValues[1]); 
2

這是因爲,如果版本,

stakeHolder.SupportDocTypeId = Convert.ToInt32(allIDValues[1]); 

默默地被轉換爲

stakeHolder.SupportDocTypeId = new int?(Convert.ToInt32(allIDValues[1])); 

要獲得三元等值,您需要將您的代碼更改爲:

MandatoryStakeholder.SupportDocTypeID = (String.IsNullOrEmpty(allIDValues[1]) || (allIDValues[1] == "0")) ? null : new int?(Convert.ToInt32(allIDValues[1]));