检查对象是否是 C# 中的数字 [英] Checking if an object is a number in C#

查看:20
本文介绍了检查对象是否是 C# 中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查一个对象是否是一个数字,以便 .ToString() 会产生一个包含数字和 +,-<的字符串/code>,.

I'd like to check if an object is a number so that .ToString() would result in a string containing digits and +,-,.

是否可以通过 .net 中的简单类型检查(例如:if (p is Number))?

Is it possible by simple type checking in .net (like: if (p is Number))?

或者我应该转换为字符串,然后尝试解析为双倍?

Or Should I convert to string, then try parsing to double?

更新: 为了澄清我的对象是 int、uint、float、double 等,它不是字符串.我正在尝试创建一个将任何对象序列化为 xml 的函数,如下所示:

Update: To clarify my object is int, uint, float, double, and so on it isn't a string. I'm trying to make a function that would serialize any object to xml like this:

<string>content</string>

<numeric>123.3</numeric>

或引发异常.

推荐答案

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

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<的额外调用/code>/其他任何东西.

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.

这篇关于检查对象是否是 C# 中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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