简体   繁体   English

是否有一个C#等同于Java的Number类?

[英]Is there a C# equivalent to Java's Number class?

I'm new to C#, coming from Java, and I'd like to check whether a certain object is a Number (it can be an Integer, Double, Float, etc). 我是C#的新手,来自Java,我想检查某个对象是否是一个数字(可以是整数,双精度,浮点数等)。 In Java I did this by saying if (toRet instanceof Number) . 在Java中,我通过说if (toRet instanceof Number)做到这一点。 I'm hoping there's a similar C# thing like if (toRet is Number) but thus far I haven't been able to find a Number class that does this. 我希望有一个类似C#的东西,如if (toRet is Number)但到目前为止我还没能找到一个这样做的Number类。 Is there a way to do this, or do I have to manually check for Integer, Double, etc? 有没有办法做到这一点,还是我必须手动检查Integer,Double等?

Edit for more info: Basically what I want to do is eventually have a byte array. 编辑更多信息:基本上我想要做的是最终有一个字节数组。 However, when the array is stored in a text file, the parser I'm using can sometimes think it's an integer array or a double array. 但是,当数组存储在文本文件中时,我使用的解析器有时会认为它是整数数组或双数组。 In Java, I had this: 在Java中,我有这个:

JSONArray dblist = (JSONArray)result_;
byte[] reallyToRet = new byte[dblist.size()];
Object toComp = dblist.get(0);

if (toComp instanceof Number)
    for (int i=0; i < dblist.size(); ++i) {
        byte elem = ((Number) dblist.get(i)).byteValue();
        reallyToRet[i] = elem;
    }

    return reallyToRet;
}

The important bit here is the if statement. 这里重要的是if语句。 Sometimes the objects in dblist would parse as integers, sometimes as doubles, and only rarely as bytes, but all I really care about at the end is the byte value. 有时dblist的对象将解析为整数,有时作为双精度解析,并且很少作为字节解析,但最后我真正关心的是字节值。

Well, yeah, but it's an extension method that just ORs all the possibilities. 嗯,是的,但它是一种扩展方法,只需要所有可能性。

This is it: 就是这个:

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
            || value is BigInteger;
}

and you would use it like this: 你会像这样使用它:

if (toRet.IsNumber());

This needs to be in a static class . 这需要在static class

I am not sure about any class for that. 我不确定任何课程。 But you can check for instance, for integer see 但是你可以检查一下,对于整数看看

int val;
if(Int32.TryParse(integer, out val))  

else

Unlikely, you can use Double.TryParse(number, out val) etc. 不太可能,你可以使用Double.TryParse(数字,输出值)等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM