Skip to content

Guid.ToString()

🏷️ C#

Guid.ToString()

在 C# 中 Guid.ToString() 提供了几种自带的格式。

说明符返回值的格式
N32 位数字: 00000000000000000000000000000000
D由连字符分隔的 32 位数字: 00000000-0000-0000-0000-000000000000
B由连字符,括在大括号分隔的 32 位数字: {00000000-0000-0000-0000-000000000000}
P由括在括号中的连字符分隔的 32 位数字: (00000000-0000-0000-0000-000000000000)
X括在大括号,其中的第四个值是 8 个十六进制值的子集也括在大括号中的四个十六进制值: {0x00000000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}

示例代码

csharp
static void Main(string[] args)
{
    Guid guid = Guid.NewGuid();

    Console.WriteLine($"guid.ToString(): {guid.ToString()}");
    Console.WriteLine($"guid.ToString(null): {guid.ToString(null)}");
    Console.WriteLine($"guid.ToString(\"\"): {guid.ToString("")}");
    Console.WriteLine($"guid.ToString(\"N\"): {guid.ToString("N")}");
    Console.WriteLine($"guid.ToString(\"D\"): {guid.ToString("D")}");
    Console.WriteLine($"guid.ToString(\"B\"): {guid.ToString("B")}");
    Console.WriteLine($"guid.ToString(\"P\"): {guid.ToString("P")}");
    Console.WriteLine($"guid.ToString(\"X\"): {guid.ToString("X")}");

    Console.ReadLine();
}

运行后输出结果如下:

txt
guid.ToString(): 60125f52-256b-4e27-9d0a-7c64611e4d3e
guid.ToString(null): 60125f52-256b-4e27-9d0a-7c64611e4d3e
guid.ToString(""): 60125f52-256b-4e27-9d0a-7c64611e4d3e
guid.ToString("N"): 60125f52256b4e279d0a7c64611e4d3e
guid.ToString("D"): 60125f52-256b-4e27-9d0a-7c64611e4d3e
guid.ToString("B"): {60125f52-256b-4e27-9d0a-7c64611e4d3e}
guid.ToString("P"): (60125f52-256b-4e27-9d0a-7c64611e4d3e)
guid.ToString("X"): {0x60125f52,0x256b,0x4e27,{0x9d,0x0a,0x7c,0x64,0x61,0x1e,0x4d,0x3e}}