在 C# 中產生 Guid ,並以不同的格式顯示:
將字串的 GUID 轉換為 Guid 型態:
假設字串格式錯誤,無法轉換為 Guid 則會拋出以下例外:
不想處理例外也可以使用 Guid.TryParse 方法,如果轉換失敗則會回傳 false ,而不是拋出例外
延伸閱讀: UUID/GUID 介紹和使用 C# 產生 GUID 示範
參考資料:
Microsoft.Learn - Guid Struct
Guid guid = Guid.NewGuid();
Console.WriteLine("guid: " + guid); // f3079291-9008-423f-ae53-07740dc1ac37
Console.WriteLine("guid: " + guid.ToString("D")); // f3079291-9008-423f-ae53-07740dc1ac37
Console.WriteLine("guid: " + guid.ToString("N")); // f30792919008423fae5307740dc1ac37
Console.WriteLine("guid: " + guid.ToString("B")); // {f3079291-9008-423f-ae53-07740dc1ac37}
Console.WriteLine("guid: " + guid.ToString("P")); // (f3079291-9008-423f-ae53-07740dc1ac37)
Console.WriteLine("guid: " + guid.ToString("X")); // {0xf3079291,0x9008,0x423f,{0xae,0x53,0x07,0x74,0x0d,0xc1,0xac,0x37}}
將字串的 GUID 轉換為 Guid 型態:
string guidString = "B7EB7C1AB80F4BCEB89189DB6A7383B8";
Guid guidFromString = Guid.Parse(guidString);
Console.WriteLine(guidFromString); // b7eb7c1a-b80f-4bce-b891-89db6a7383b8
假設字串格式錯誤,無法轉換為 Guid 則會拋出以下例外:
Unhandled exception. System.FormatException: Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
at System.Guid.GuidResult.SetFailure(ParseFailure failureKind)
at System.Guid.TryParseExactN(ReadOnlySpan`1 guidString, GuidResult& result)
at System.Guid.TryParseGuid(ReadOnlySpan`1 guidString, GuidResult& result)
at System.Guid.Parse(ReadOnlySpan`1 input)
at System.Guid.Parse(String input)
at ConsoleAppGuidTest0930.Program.Main(String[] args) in C:\Users\ruyut\Test\Program.cs:line 28
不想處理例外也可以使用 Guid.TryParse 方法,如果轉換失敗則會回傳 false ,而不是拋出例外
string guidString = "B7EB7C1AB80F4BCEB89189DB6A7383B8";
if (Guid.TryParse(guidString, out Guid guid))
{
Console.WriteLine(guid); // b7eb7c1a-b80f-4bce-b891-89db6a7383b8
}
else
{
Console.WriteLine("Invalid GUID");
}
延伸閱讀: UUID/GUID 介紹和使用 C# 產生 GUID 示範
參考資料:
Microsoft.Learn - Guid Struct
留言
張貼留言
如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com