【问题标题】:Will converting Char.GetNumericValue() to int destroy information?将 Char.GetNumericValue() 转换为 int 会破坏信息吗?
【发布时间】:2020-07-27 08:05:06
【问题描述】:

我正在实施GetHashCode()。我想将名为string Id 的属性中的值相加,然后除以 通过一些常数并返回结果。我正在使用GetNumericValue():

int sum = 0;
 foreach (var ch in Id)
  sum += char.GetNumericValue(ch);

但似乎GetNumericValue 返回double。可以转换成int吗?

我以为Unicode字符是用整数表示的,为什么会返回double? 并且可以忽略它吗?

【问题讨论】:

  • 您似乎不明白GetNumericValue 的作用。与其尝试继续使用它,不如说明您打算如何使用ch,我们可以建议一个合适的方法。
  • 为什么要为字符串实现不同的哈希码?为什么不只是Id.GetHashCode()

标签: c# unicode char gethashcode


【解决方案1】:

为什么会返回double?

虽然 0-9 是标准数字,但实际上有一些 Unicode 字符表示数字,其中一些是浮点数,例如 ½。举个例子吧:

var ch = char.GetNumericValue('½');
Console.WriteLine(ch);// 0.5 output

【讨论】:

    【解决方案2】:

    是的,某些值会丢失数据,因为这是 本身就是数字的 unicode 字符的 数值 - 和 unicode包括非整数字符:

    var val = char.GetNumericValue('½'); // or ¼, or ꠲, or ⳽
    System.Console.WriteLine(val);
    

    【讨论】:

    • 等等,GetNumericValue() 是用于将 char 转换为 int 的吗?不是为了获取Unicode字符的数值吗?
    • @avivgood2 如果您的意思是代码点:不;那将是var codePoint = (int)c;
    猜你喜欢
    • 1970-01-01
    • 2016-07-07
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 2022-01-22
    • 2010-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多