我没有找到Guid的TryParse方法。我想知道其他人如何处理将字符串格式的guid转换为guid类型。
Guid Id;
try
{
Id = new Guid(Request.QueryString["id"]);
}
catch
{
Id = Guid.Empty;
}
我没有找到Guid的TryParse方法。我想知道其他人如何处理将字符串格式的guid转换为guid类型。
Guid Id;
try
{
Id = new Guid(Request.QueryString["id"]);
}
catch
{
Id = Guid.Empty;
}
不幸的是,没有TryParse()等价的。如果您创建一个系统的新实例。Guid并传入字符串值,您可以捕获它在无效时抛出的三个可能的异常。
这些都是:
ArgumentNullException FormatException OverflowException
我看到过一些实现,如果你只是想验证它,而不是创建它,你可以在创建实例之前对字符串做一个regex。
这将使您非常接近,我在生产中使用它,从未发生过碰撞。然而,如果你查看reflector中guid的构造函数,你会看到它所做的所有检查。
public static bool GuidTryParse(string s, out Guid result)
{
if (!String.IsNullOrEmpty(s) && guidRegEx.IsMatch(s))
{
result = new Guid(s);
return true;
}
result = default(Guid);
return false;
}
static Regex guidRegEx = new Regex("^[A-Fa-f0-9]{32}$|" +
"^({|\\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\\))?$|" +
"^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$", RegexOptions.Compiled);
如果你想要的只是一些非常基本的错误检查,你可以检查字符串的长度。
string guidStr = "";
if( guidStr.Length == Guid.Empty.ToString().Length )
Guid g = new Guid( guidStr );
Guid.TryParse()
https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse
or
Guid.TryParseExact()
https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparseexact
在。net 4.0(或3.5?)
使用如下代码:
new Guid("9D2B0228-4D0D-4C23-8B49-01A698857709")
而不是“9D2B0228-4D0D-4C23-8B49-01A698857709”,你可以设置你的字符串值