typeof()检查数值

什么是检查typeof()是否在数学上可用(数字)的最简单方法。

我需要使用TryParse方法或检查它:

if (!(DC.DataType == typeof(int) || DC.DataType == typeof(double) || DC.DataType == typeof(long) || DC.DataType == typeof(short) || DC.DataType == typeof(float))) { MessageBox.Show("Non decimal data cant be calculated"); return; } 

如果有更简单的方法来实现这一点,你可以自由地建议

不幸的是,没什么可做的。 但是从C#3开始,你可以做一些更高级的事情:

 public static class NumericTypeExtension { public static bool IsNumeric(this Type dataType) { if (dataType == null) throw new ArgumentNullException("dataType"); return (dataType == typeof(int) || dataType == typeof(double) || dataType == typeof(long) || dataType == typeof(short) || dataType == typeof(float) || dataType == typeof(Int16) || dataType == typeof(Int32) || dataType == typeof(Int64) || dataType == typeof(uint) || dataType == typeof(UInt16) || dataType == typeof(UInt32) || dataType == typeof(UInt64) || dataType == typeof(sbyte) || dataType == typeof(Single) ); } } 

所以您的原始代码可以这样写:

 if (!DC.DataType.IsNumeric()) { MessageBox.Show("Non decimal data cant be calculated"); return; } 

您可以检查数字类型实现的接口:

 if (data is IConvertible) { double value = ((IConvertible)data).ToDouble(); // do calculations } if (data is IComparable) { if (((IComparable)data).CompareTo(42) < 0) { // less than 42 } }