如何在.net中验证Guid

Ajm*_*nfo 11 c#

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

Kyl*_*ndo 30

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;
}
Run Code Online (Sandbox Code Playgroud)

  • +1,在.NET 4.0中,我们最终会看到`Guid.TryParse()`的引入,这显然比使用Regex更好.但就目前而言,这是完全足够和可接受的.http://connect.microsoft.com/VisualStudio/feedback/details/94072/guid-tryparse (6认同)

Han*_*ant 11

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

鸭!