如何在.net中validationGuid

请告诉我如何在.net中validationGUID,它总是独一无二的?

Guid的独特之处在99.99999999999999999999999999999999%。

这取决于你的意思是什么?

确定Guid字符串实际上是Guid的代码如下 :

private static Regex isGuid = new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled); internal static bool IsGuid(string candidate, out Guid output) { bool isValid = false; output = Guid.Empty; if(candidate != null) { if (isGuid.IsMatch(candidate)) { output=new Guid(candidate); isValid = true; } } return isValid; } 

2 ^ 128是一个非常非常大的数字。 它比宇宙生命中的皮秒数大十亿倍。 通过长镜头太​​大而无法validation,答案注定是“42”。 使用它们的重点是:你不必这样做。 如果您担心重复,那么您会担心错误的原因。 你的机器被meteor撞击破坏的几率要大得多。

鸭!

这是一个非常快速的非正则表达式答案:

 public static bool IsHex(this char c) { return ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')); } public static bool IsGuid(this string s) { // Length of a proper GUID, without any surrounding braces. const int len_without_braces = 36; // Delimiter for GUID data parts. const char delim = '-'; // Delimiter positions. const int d_0 = 8; const int d_1 = 13; const int d_2 = 18; const int d_3 = 23; // Before Delimiter positions. const int bd_0 = 7; const int bd_1 = 12; const int bd_2 = 17; const int bd_3 = 22; if (s == null) return false; if (s.Length != len_without_braces) return false; if (s[d_0] != delim || s[d_1] != delim || s[d_2] != delim || s[d_3] != delim) return false; for (int i = 0; i < s.Length; i = i + (i == bd_0 || i == bd_1 || i == bd_2 || i == bd_3 ? 2 : 1)) { if (!IsHex(s[i])) return false; } return true; } 

您无法validationGUID的唯一性。 您只希望它是使用生成唯一16字节的工具生成的。 至于validation,这个简单的代码可能会起作用(假设您正在处理GUID的字符串表示:

 bool ValidateGuid(string theGuid) { try { Guid aG = new Guid(theGuid); } catch { return false; } return true; } 

如果您正在寻找一种方法来确定它是否是实际.Net Guid类型的格式, 请查看本文 。 快速正则表达式可以解决问题。

这个问题已在本文中讨论过了。 您可能会发现更多有趣的细节

在.net 4中,您可以使用此扩展方法

 public static class GuidExtensions { public static bool IsGuid(this string value) { Guid output; return Guid.TryParse(value, out output); } }