[英]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
)在收到 char
'N'
我想获得相关值(即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似乎
Enum.Parse
不适用于char
,甚至char.toString()
,所以我想获取与 char 关联的数值
var myChar = 'N';
var myNumber = Char.GetNumericValue(myChar); // or char.GetNumericValue(myChar);
and the value of myNumber
is -1
, which is incorrect并且
myNumber
的值为-1
,这是不正确的
What is going on?到底是怎么回事?
The Microsoft documentation says that Char.GetNumericValue()
converts a specified numeric Unicode character to a double-precision floating-point number . Microsoft 文档说
Char.GetNumericValue()
将指定的数字 Unicode 字符转换为双精度浮点数。
The character 'N' is not numeric, it is an alphabetical character.字符“N”不是数字,它是字母字符。
If you want to get a Status
enum value, you could just use:如果你想获得一个
Status
枚举值,你可以使用:
Status status = (Status)myChar;
The documentation says GetNumericValue()
returns: "The numeric value of c if that character represents a number ; otherwise, -1.0." 文档说
GetNumericValue()
返回:“如果该字符表示数字,则 c 的数值;否则为 -1.0。”
'N' does not represent a number, so it returns -1. 'N' 不代表数字,因此它返回 -1。
A char
can be implicitly converted to a number: char
可以隐式转换为数字:
int number = 'N';
Or, if you want to use var
, you just need an explicit cast.或者,如果你想使用
var
,你只需要一个明确的演员表。
Note also that your enum values are int
s, not char
s.另请注意,您的枚举值是
int
s,而不是char
s。 They are implicitly converted.它们被隐式转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.