我有一个函数,除其他外,它接受一个对象和一个类型,并将该对象转换为该类型.但是,输入对象通常是double,并且类型有一些int(uint,long等)的变体.如果圆数作为double传递(如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."); }
谢谢.
这似乎符合你的要求.我只测试了它的双打,浮子和整数.
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; }