检查typeof()是否在数学上可用(数值)的最简单方法是什么?
我是否需要使用TryParse method或通过以下方式进行检查:
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;
}如果有更简单的方法来实现这一点,你可以自由地建议
发布于 2012-01-12 21:42:41
不幸的是,没有什么可做的。但是从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;
}发布于 2012-01-12 21:50:48
您可以检查数值类型实现的接口:
if (data is IConvertible) {
double value = ((IConvertible)data).ToDouble();
// do calculations
}
if (data is IComparable) {
if (((IComparable)data).CompareTo(42) < 0) {
// less than 42
}
}https://stackoverflow.com/questions/8835982
复制相似问题