简体   繁体   中英

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). In Java I did this by saying 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. Is there a way to do this, or do I have to manually check for Integer, Double, etc?

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:

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. 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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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