2017-08-02 85 views
-2

如何检查两个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}"); 
+0

'Guid'正确实现平等,所以'的Equals '或'=='。 –

回答

-11

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:真

+10

绝对没有必要转换为字符串,你增加了不必要的开销 - 这是一个可怕的想法。只需使用'g1 == g2'或'g1.Equals(g2)' – DavidG

7

您使用的Guid.Equals重载。

所以在实用性方面:

Guid g1 = ... 
Guid g2 = ... 

if (g1.Equals(g2)) { /* guids are equal */ } 

注意System.Guid实现平等的运营商一样,所以下面也将工作:

if (g1 == g2) { /* guids are equal */ } 
+0

感谢您指向正确的方向,我认为'Equals'与引用类型相匹配。 –

+0

@AmitKB看一看['public bool Equals(Guid g)'](http://referencesource.microsoft.com/mscorlib/a.html#54bcc19a4028b3f2) –

+0

@MartinBackasch谢谢参考。 –

相关问题