且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查对象是否是 C# 中的数字

更新时间:2023-02-09 15:25:03

您只需对每个基本数字类型进行类型检查.

You will simply need to do a type check for each of the basic numeric types.

这是一个可以完成这项工作的扩展方法:

Here's an extension method that should do the job:

public static bool IsNumber(this object value)
{
    return value is sbyte
            || value is byte
            || value is short
            || value is ushort
            || value is int
            || value is uint
            || value is long
            || value is ulong
            || value is float
            || value is double
            || value is decimal;
}

这应该涵盖所有数字类型.

This should cover all numeric types.

您似乎确实想在反序列化期间解析字符串中的数字.在这种情况下,***使用 double.TryParse.

It seems you do actually want to parse the number from a string during deserialisation. In this case, it would probably just be best to use double.TryParse.

string value = "123.3";
double num;
if (!double.TryParse(value, out num))
    throw new InvalidOperationException("Value is not a number.");

当然,这不会处理非常大的整数/长小数,但如果是这种情况,您只需添加对 long.TryParse/decimal.TryParse/其他任何东西.

Of course, this wouldn't handle very large integers/long decimals, but if that is the case you just need to add additional calls to long.TryParse / decimal.TryParse / whatever else.