我没有找到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;
}
new Guid(string)
你也可以考虑使用 TypeConverter
。
使用这样的代码:
new Guid("9D2B0228-4D0D-4C23-8B49-01A698857709")
您可以设置您的字符串值,而不是使用 "9D2B0228-4D0D-4C23-8B49-01A698857709"。
Guid.TryParse()
https://learn.microsoft.com/zh-cn/dotnet/api/system.guid.tryparse
或者
Guid.TryParseExact()
https://learn.microsoft.com/zh-cn/dotnet/api/system.guid.tryparseexact
在.NET 4.0(或3.5?)中。
这将让你接近目标,我在生产中使用它并从未遇到过冲突。但是,如果你查看反射器中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);
很遗憾,没有TryParse()的等效方法。如果您创建一个System.Guid的新实例并传入字符串值,则可以捕获三种可能的异常(如果无效)。
这些包括:
我看过一些实现,可以在创建实例之前对该字符串执行正则表达式,如果您只是想验证而不是创建它的话。
string guidStr = "";
if( guidStr.Length == Guid.Empty.ToString().Length )
Guid g = new Guid( guidStr );
TryParse()
或TryParseExact()
。如果您提供了无效的Guid,则在尝试在比较或类似操作中访问它时,将会出现以下异常:FormatException:Guid应该包含32个数字和4个破折号(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)。
- Ogglas