【问题标题】:Why is char.GetNumericValue() giving the wrong result?为什么 char.GetNumericValue() 给出错误的结果?
【发布时间】:2021-05-24 14:20:41
【问题描述】:

我有以下枚举

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

在收到字符'N' 后,我想获得相关值(即Status.New

似乎Enum.Parse 不适用于char,甚至char.toString(),所以我想获取与字符关联的数值

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

myNumber的值为-1,不正确

发生了什么事?

【问题讨论】:

    标签: c# enums char


    【解决方案1】:

    Microsoft documentation 表示Char.GetNumericValue() 将指定的数字 Unicode 字符转换为双精度浮点数

    字符'N'不是数字,它是一个字母字符。

    如果你想得到一个Status 枚举值,你可以使用:

    Status status = (Status)myChar;
    

    【讨论】:

      【解决方案2】:

      documentation 表示GetNumericValue() 返回:“c 的数值如果该字符表示数字;否则为-1.0。”
      'N' 不代表数字,所以它返回 -1。

      char 可以隐式转换为数字:

      int number = 'N';
      

      或者,如果你想使用var,你只需要一个显式转换。

      还要注意,您的枚举值是 ints,而不是 chars。它们是隐式转换的。

      【讨论】:

        猜你喜欢
        • 2018-07-04
        • 2012-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-09
        • 2020-09-15
        • 2023-03-24
        相关资源
        最近更新 更多