我有一个函数,除其他外,它接受一个对象和一个类型,并将对象转换为该类型。然而,输入对象通常是一个双精度类型,并且类型有一些 int 变体(uint、long 等)。如果将整数作为双精度(如 4.0)传入,我希望它能够工作,但如果传入小数(4.3)则抛出异常。有没有更优雅的方法来检查 Type 是否是某种 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.");
}
谢谢。