简体   繁体   中英

Why is char.GetNumericValue() giving the wrong result?

I have the following enum

public enum Status
{
    New = 'N',
    Live = 'L',
    Expired = 'E'
}

And upon receiving the char 'N' I would like to get the relevant value (ie Status.New )

It seems that Enum.Parse will not work with char , or even char.toString() for that matter, so I want to get the numeric value associated with the char

var myChar = 'N';
var myNumber = Char.GetNumericValue(myChar); // or char.GetNumericValue(myChar);

and the value of myNumber is -1 , which is incorrect

What is going on?

The Microsoft documentation says that Char.GetNumericValue() converts a specified numeric Unicode character to a double-precision floating-point number .

The character 'N' is not numeric, it is an alphabetical character.

If you want to get a Status enum value, you could just use:

Status status = (Status)myChar;

The documentation says GetNumericValue() returns: "The numeric value of c if that character represents a number ; otherwise, -1.0."
'N' does not represent a number, so it returns -1.

A char can be implicitly converted to a number:

int number = 'N';

Or, if you want to use var , you just need an explicit cast.

Note also that your enum values are int s, not char s. They are implicitly converted.

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