如何在C#中将对象字符串转换为Object Guid

Gib*_*boK 1 c# asp.net

我有一个DetailsView,我需要在DataKeyNames"UserId"(一个Guid字段)中获取值,并将其添加到Object Guid.

目前我正在使用此代码:

String myUserId = (String)uxAuthorListDetailsView.DataKey["UserId"].ToString();
Run Code Online (Sandbox Code Playgroud)

但我需要这样的东西:

Guid myUserGuid = (Guid)uxAuthorListDetailsView.DataKey["UserId"].ToString();
Run Code Online (Sandbox Code Playgroud)

但是不起作用我得到错误错误

Cannot convert type 'string' to 'System.Guid'
Run Code Online (Sandbox Code Playgroud)

可能是什么问题呢?谢谢你们的支持!

Jon*_*eet 6

好吧,问题是你正在调用ToString()然后尝试将该字符串转换为a Guid,当没有可用的转换时.可能的选择:

If this is user-entered data at all, or there's any other reason why the value is half-expected to be incorrect, and if you're using .NET 4, you might want to use Guid.TryParse instead, which will allow you to handle failure without an exception.