如何检查两个GUID
是否匹配?
使用以下C#代码,如果g2
与GUID
具有相同的g1
,如何匹配:
Guid g1 = new Guid("{10349469-c6f7-4061-b2ab-9fb4763aeaed}");
Guid g2 = new Guid("{45DF902E-2ECF-457A-BB0A-E04487F71D63}");
答案 0 :(得分:8)
您使用Guid.Equals
重载中的任何一个。
所以实际上:
Guid g1 = ...
Guid g2 = ...
if (g1.Equals(g2)) { /* guids are equal */ }
请注意,System.Guid
也实现了相等运算符,因此以下内容也适用:
if (g1 == g2) { /* guids are equal */ }
答案 1 :(得分:-11)
ToString()
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 as string:10349469-c6f7-4061-b2ab-9fb4763aeaed
g2 as string:45df902e-2ecf-457a-bb0a-e04487f71d63
g1a as string:10349469-c6f7-4061-b2ab-9fb4763aeaed
g1b as string:10349469-c6f7-4061-b2ab-9fb4763aeaed
g1与g1a匹配:True
g1与g1b匹配:True