【发布时间】:2010-09-24 04:23:37
【问题描述】:
我有一个函数,除其他外,它接受一个对象和一个类型,并将对象转换为该类型。然而,输入对象通常是一个双精度类型,并且类型有一些 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.");
}
谢谢。
【问题讨论】:
-
只需几个 cmets - 1) 不要忘记花车。 2) 您可能想要使用 Math.Round(),因为有时会出现 1.000000001 而不是 1.0 由于浮点问题。
-
听起来你在 System.Convert 中复制功能...
-
好点,乔恩,我会确保记住花车。戴夫,当您将 System.Convert.ChangeType 从 double 转换为 int 时,它会默默地进行银行家四舍五入。此代码是为了防止在 System.Convert 调用之前发生这种情况。
标签: c# reflection casting types