检查 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;
}
如果有更简单的方法可以做到这一点,欢迎提出建议
最佳答案
不幸的是,没什么可做的。但是从 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;
}
关于c# - typeof() 检查数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8835982/