typeof运算()来检查数字值 [英] typeof() to check for Numeric values

查看:219
本文介绍了typeof运算()来检查数字值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

what is the easiest way to check if a typeof() is mathematically usable(numeric).

我是否需要使用的TryParse方法或由该检查:

do i need to use the TryParse method or check it by this:

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;
     }

如果有一个更简单的方法来实现这一目标,您的免费建议

if there is a more easy way to achieve this, your free to suggest

推荐答案

有没有什么很多工作要做,很遗憾。但是从C#3起,你可以做一些票友:

There's nothing much to do, unfortunately. But from C# 3 onwards, you can do something fancier:

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)
               );
    }
}



所以你的原代码,可以这样写:

so your original code can be written like this:

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

这篇关于typeof运算()来检查数字值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆