我有以下兩種方法將int
轉換爲short?
。將int轉換爲short的更好方法? (NULL,如果不可能)
- 如果該值不在短程範圍內,則第一個失敗。
- 第二種方法可行,但它有一個不必要的
conversion to string
。
有沒有更好的方法?
編輯:
從下面的答案:
的Int16只是爲Int32一個子集,所以你不需要任何轉換爲 「中間」 類型。
CODE
//Approach 1
int vIn = 123456789;
short? vOut = Convert.ToInt16(vIn);
//Value was either too large or too small for an Int16.
//Approach 2
short? vOut2 = null;
int vIn2 = 123456789;
short number;
string characterRepresentationOfInt = vIn2.ToString();
bool result = Int16.TryParse(characterRepresentationOfInt, out number);
if (result)
{
vOut2 = number;
}
參考:
是的......「Int16只是Int32的一個子集,所以你不需要任何轉換到」中間「類型。」這是我錯過的關鍵點......非常感謝。 – Lijo 2013-02-22 13:37:16
@AdrianoRepetti對不起,我發表評論到錯誤的答案。沒關係。 – ViRuSTriNiTy 2018-02-15 06:27:39