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

2019-02-16 03:53发布

UPDATE

Guid.TryParse is available in .NET 4.0

END UPDATE

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

So, I was looking into regular expressions [aka googling around to find one] and each time I found one there was a heated argument in the comments section about RegEx A doesn't work, use RegEx B. Then someone would write Regex C yadda yadda

So anyway, What I decided to do was this, but I feel bad about it.

public static bool IsGuid (string possibleGuid) {

    try {
      Guid gid = new Guid(possibleGuid);
      return true;    
    } catch (Exception ex) {
      return false;
    }
}

Obviously I don't really like this since it's been drilled into me since day one to avoid throwing exceptions if you can defensibly code around it.

Does anyone know why there is no public Guid.TryParse() in the .NET Framework?

Does anyone have a real Regular Expression that will work for all GUIDs?

7条回答
ら.Afraid
2楼-- · 2019-02-16 04:34

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);
}
查看更多
登录 后发表回答