我有一個函數,其中包括一個對象和一個類型,並將該對象轉換爲該類型。但是,輸入對象通常是雙精度型,並且類型的一些變體是int(uint,long等)。如果一個循環數以double形式傳遞(如4.0),我希望這能起作用,但如果在(4.3)中傳遞了小數,則拋出異常。有沒有更好的方法來檢查類型是否是某種類型的int?檢查C#中的任何int類型?
if (inObject is double && (targetType == typeof (int)
|| targetType == typeof (uint)
|| targetType == typeof (long)
|| targetType == typeof (ulong)
|| targetType == typeof (short)
|| targetType == typeof (ushort)))
{
double input = (double) inObject;
if (Math.Truncate(input) != input)
throw new ArgumentException("Input was not an integer.");
}
謝謝。
只是一些評論 - 1)不要忘記花車。 2)您可能想要使用Math.Round(),因爲有時由於浮點問題而出現1.000000001而不是1.0。 – 2008-11-26 15:45:59
也聽起來像你正在複製System.Convert中的功能... – 2008-11-26 16:35:39