检查如果对象是一个数字,在C# [英] Checking if an object is a number in C#

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

问题描述

我要检查,如果对象是一个号码,以便的ToString()将导致包含数字和字符串+ -

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

是否有可能通过简单的类型在.NET中检查(如:如果(p是号码))?

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,浮点型,双,等它不是一个字符串。 我试图让这将任何对象序列化到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>

或引发异常。

or raise an exception.

推荐答案

您只需要简单地做一个类型检查的每个基本数字类型。

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.

看来你真的想deserialisation期间解析从字符串的数量。在这种情况下,它很可能只是最好使用 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 / <的情况下code> 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.

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

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