Is there a GUID.TryParse() in .NET 3.5?

后端 未结 7 1512
遇见更好的自我
遇见更好的自我 2021-01-07 16:25

UPDATE

Guid.TryParse is available in .NET 4.0

END UPDATE

Obviously there is no public GUID.TryParse() in .NET CLR

相关标签:
7条回答
  • 2021-01-07 16:29

    In terms of why there isn't one, it's an oversight. There will be a Guid.TryParse in .NET 4 (see BCL blog post for details).

    0 讨论(0)
  • 2021-01-07 16:30

    This should work:

    @"^\{?[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 讨论(0)
  • 2021-01-07 16:37

    This implementation of a TryParse for Guids uses a try-catch in order to catch missformed Guids. It is implemented as extension method und must be placed in a static class:

    public static bool TryParseGuid(this string s, out Guid guid)
    {
        try {
            guid = new Guid(s);
            return true;
        } catch {
            guid = Guid.Empty;
            return false;
        }
    }
    

    It can be called with

    string s = "{CA761232-ED42-11CE-BACD-00AA0057B223}";
    Guid id;
    if (s.TryParseGuid(out id) {
        // TODO: use id
    } else {
        // Sorry not a valid Guid.
    }
    

    Starting with C# 7.0 / Visual Studio 2017, you can call it with:

    string s = "{CA761232-ED42-11CE-BACD-00AA0057B223}";
    if (s.TryParseGuid(out Guid id) {
        // TODO: use id
    } else {
        // Sorry not a valid Guid.
    }
    

    UPDATE

    Since Visual Studio 2010 / .NET Framework 4.0, System.Guid provides a TryParse and a TryPareExact method.

    0 讨论(0)
  • 2021-01-07 16:43

    There's no TryParse functionality in the .NET Framework to my knowledge at this moment. You'll have to resort to RegEx or the try-catch option. RegEx isn't my cup of tea, so I'm sure someone else will post an answer.

    Exceptions are expensive performance wise, so my vote goes to the RegEx option.

    0 讨论(0)
  • 2021-01-07 16:50

    Guid.TryParse implementation using regular expressions.

    0 讨论(0)
  • 2021-01-07 16:50

    IsGuid implemented as extension method for string...

    public static bool IsGuid(this string stringValue)
    {
       string guidPattern = @"[a-fA-F0-9]{8}(\-[a-fA-F0-9]{4}){3}\-[a-fA-F0-9]{12}";
       if(string.IsNullOrEmpty(stringValue))
         return false;
       Regex guidRegEx = new Regex(guidPattern);
       return guidRegEx.IsMatch(stringValue);
    }
    
    0 讨论(0)
提交回复
热议问题