在C#中如何获得以Unicode格式打印的字符的最小值和最大值



根据msdn,char的最小值为u 0000,char的最大值为u ffff

我编写了以下代码以打印相同的代码:

using System;
using System.Collections.Generic;
using System.Linq;
namespace myApp {
    class Program {
        static void Main() {
            char min = char.MinValue;
            char max = char.MaxValue;
            Console.WriteLine($"The range of char is {min} to {max}");
        }
    }
}

,但我没有以u 0000和u ffff的格式获得输出。

如何获得它?

您的问题是,格式化为字符串时的char已表示为字符。我的意思是具有值0x30char表示为0,而不是48

因此,您需要将这些值施加为int并显示它们十六进制(使用格式指定器X):

int min = char.MinValue; // int - not char
int max = char.MaxValue;
Console.WriteLine($"The range of char is U+{min:x4} to U+{max:x4}");

看到它们的数值(十六进制)值。

结果:

The range of char is U+0000 to U+ffff

请参阅:https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/tokens/interpolated

最新更新