如何檢查兩個GUID
是否匹配?如何檢查兩個GUID是否與.NET(C#)匹配?
使用以下C#代碼,如何匹配如果g2
具有相同GUID
作爲g1
:
Guid g1 = new Guid("{10349469-c6f7-4061-b2ab-9fb4763aeaed}");
Guid g2 = new Guid("{45DF902E-2ECF-457A-BB0A-E04487F71D63}");
如何檢查兩個GUID
是否匹配?如何檢查兩個GUID是否與.NET(C#)匹配?
使用以下C#代碼,如何匹配如果g2
具有相同GUID
作爲g1
:
Guid g1 = new Guid("{10349469-c6f7-4061-b2ab-9fb4763aeaed}");
Guid g2 = new Guid("{45DF902E-2ECF-457A-BB0A-E04487F71D63}");
ToString()
GUID的方法將導致consisten字符串值,因此它可以用於匹配。
檢查this DotNetFiddle進行此測試。
using System;
public class Program
{
public static void Main()
{
// Two distinct GUIDs
Guid g1 = new Guid("{10349469-c6f7-4061-b2ab-9fb4763aeaed}");
Guid g2 = new Guid("{45DF902E-2ECF-457A-BB0A-E04487F71D63}");
// GUID similar to 'g1' but with mixed case
Guid g1a = new Guid("{10349469-c6f7-4061-b2ab-9fb4763AEAED}");
// GUID similear to 'g1' but without braces
Guid g1b = new Guid("10349469-c6f7-4061-b2ab-9fb4763AEAED");
// Show string value of g1,g2 and g3
Console.WriteLine("g1 as string: {0}\n", g1.ToString());
Console.WriteLine("g2 as string: {0}\n", g2.ToString());
Console.WriteLine("g1a as string: {0}\n", g1a.ToString());
Console.WriteLine("g1b as string: {0}\n", g1b.ToString());
// g1 to g1a match result
bool resultA = (g1.ToString() == g1a.ToString());
// g1 to g1b match result
bool resultB = (g1.ToString() == g1b.ToString());
// Show match result
Console.WriteLine("g1 matches to g1a: {0}\n", resultA);
Console.WriteLine("g1 matches to g1b: {0}", resultB);
}
}
輸出
G1作爲字符串:10349469-c6f7-4061-b2ab-9fb4763aeaed
G2作爲字符串:45df902e-2ecf-457A-bb0a-e04487f71d63
G1A作爲字符串:10349469-c6f7-4061-b2ab-9fb4763aeaed
g1b as string:10349469-c6f7-4061-b2ab-9fb4763aeaed
G1匹配G1A:真
G1匹配G1B:真
絕對沒有必要轉換爲字符串,你增加了不必要的開銷 - 這是一個可怕的想法。只需使用'g1 == g2'或'g1.Equals(g2)' – DavidG
您使用的Guid.Equals
重載。
所以在實用性方面:
Guid g1 = ...
Guid g2 = ...
if (g1.Equals(g2)) { /* guids are equal */ }
注意System.Guid
實現平等的運營商一樣,所以下面也將工作:
if (g1 == g2) { /* guids are equal */ }
感謝您指向正確的方向,我認爲'Equals'與引用類型相匹配。 –
@AmitKB看一看['public bool Equals(Guid g)'](http://referencesource.microsoft.com/mscorlib/a.html#54bcc19a4028b3f2) –
@MartinBackasch謝謝參考。 –
'Guid'正確實現平等,所以'的Equals '或'=='。 –