我沒有找到Guid的TryParse方法。我想知道其他人如何處理將字符串格式的guid轉換爲guid類型。如何嘗試將字符串轉換爲Guid
Guid Id;
try
{
Id = new Guid(Request.QueryString["id"]);
}
catch
{
Id = Guid.Empty;
}
我沒有找到Guid的TryParse方法。我想知道其他人如何處理將字符串格式的guid轉換爲guid類型。如何嘗試將字符串轉換爲Guid
Guid Id;
try
{
Id = new Guid(Request.QueryString["id"]);
}
catch
{
Id = Guid.Empty;
}
new Guid(string)
你也可以看看使用TypeConverter
。
不幸的是,沒有一個TryParse()等價物。如果你創建一個System.Guid的新實例並傳入字符串值,你可以捕獲它可能拋出的三個異常,如果它是無效的。
這些都是:
我已經看到了一些實現,你可以創建實例之前做字符串正則表達式,如果你只是試圖驗證它,而不是創建它。
這會讓你非常接近,我在生產中使用它,並且從未發生過碰撞。但是,如果您查看反射器中的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);
如果你想要的只是一些非常基本的錯誤檢查,你可以檢查字符串的長度。 (?或3.5)
string guidStr = "";
if(guidStr.Length == Guid.Empty.ToString().Length)
Guid g = new Guid(guidStr);
Guid.TryParse()
https://msdn.microsoft.com/de-de/library/system.guid.tryparse(v=vs.110).aspx
或
Guid.TryParseExact()
https://msdn.microsoft.com/de-de/library/system.guid.tryparseexact(v=vs.110).aspx
在.NET 4.0
使用這樣的代碼:
new Guid("9D2B0228-4D0D-4C23-8B49-01A698857709")
,而不是 「9D2B0228-4D0D-4C23-8B49-01A698857709」 你可以設置你的字符串值
具體來說,GUIDConverter,它是內置的。http://msdn.microsoft.com/en -us/library/system.componentmodel.guidconverter.aspx – 2008-12-08 19:11:15
TypeDescriptor.GetConverter(typeof(Guid)) – leppie 2008-12-08 19:34:16