我有一个函数,除其他外,它接受一个对象和一个类型,并将该对象转换为该类型。但是,输入对象通常是 double,并且类型是 int 的一些变体(uint、long 等)。如果将整数作为 double 值(如 4.0)传入,我希望它能工作,但如果传入小数点(4.3),则抛出异常。有没有更优雅的方法来检查类型是否是某种 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.");
}
谢谢。
最佳答案
这似乎可以满足您的要求。我只测试了 double 、 float 和整数。
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;
}
关于c# - 检查 C# 中的任何 int 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/321139/