2008-11-26 42 views
4

我有一個函數,其中包括一個對象和一個類型,並將該對象轉換爲該類型。但是,輸入對象通常是雙精度型,並且類型的一些變體是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."); 
} 

謝謝。

+0

只是一些評論 - 1)不要忘記花車。 2)您可能想要使用Math.Round(),因爲有時由於浮點問題而出現1.000000001而不是1.0。 – 2008-11-26 15:45:59

+0

也聽起來像你正在複製System.Convert中的功能... – 2008-11-26 16:35:39

回答

6

這似乎是做你所問。我只測試過雙打,浮標和整數。

public int GetInt(IConvertible x) 
    { 
     int y = Convert.ToInt32(x); 
     if (Convert.ToDouble(x) != Convert.ToDouble(y)) 
      throw new ArgumentException("Input was not an integer"); 
     return y; 
    } 
0

你應該能夠使用Convert.ToDecimal和x%y的組合,我會想,其中y = 1並檢查結果== 0;

2
int intvalue; 
if(!Int32.TryParse(inObject.ToString(), out intvalue)) 
    throw InvalidArgumentException("Not rounded number or invalid int...etc"); 

return intvalue; //this now contains your value as an integer!