如何检查两个GUID
是否匹配?
使用以下C#代码,如何匹配g2
与g1
具有相同的GUID
:
Guid g1 = new Guid("{10349469-c6f7-4061-b2ab-9fb4763aeaed}");
Guid g2 = new Guid("{45DF902E-2ECF-457A-BB0A-E04487F71D63}");
Guid.Equals
的两个重载之一。因此,从实际角度来看:Guid g1 = ...
Guid g2 = ...
if (g1.Equals(g2)) { /* guids are equal */ }
请注意,System.Guid
实现了等号运算符,因此以下代码也可以正常工作:if (g1 == g2) { /* guids are equal */ }
Equals
是按引用类型匹配的。 - Amit BhagatToString()
方法可以将 GUID 转换为一致的字符串值,因此可以用于匹配。
请查看 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作为字符串:10349469-c6f7-4061-b2ab-9fb4763aeaed
g1与g1a匹配:真
g1与g1b匹配:真
g1 == g2
或g1.Equals(g2)
即可。 - DavidG
Guid
正确实现了相等性,因此可以使用Equals
或==
进行比较。 - Adam Houldsworth