在VB.Net中将字符串转换为Guid

6

我有一个GUID叫做"UserID",它需要填充Session("UserID")中的字符串,并格式化为完美的GUID。

如果我尝试这样做,会显示"无法将类型字符串转换为类型 Guid"

       Dim UserID As New Guid()
       If HttpContext.Current.Session("UserID") IsNot Nothing Then
          UserID = HttpContext.Current.Session("UserID")
       End If

如果我尝试这样做“无法将字符串类型转换为Guid类型”。
       Dim UserID As New Guid()
       If HttpContext.Current.Session("UserID") IsNot Nothing Then
          UserID = DirectCast(HttpContext.Current.Session("UserID"), Guid)
       End If

这将字符串完美地转换为Guid,但它在 If 语句之外无法访问。

       If HttpContext.Current.Session("UserID") IsNot Nothing Then
         Dim UserID As new Guid(HttpContext.Current.Session("UserID"))
       End If

我不知道如何在If语句之外定义UserID,并有条件地进行赋值。

1个回答

13

试着用这个方法

Dim UserID As New Guid()
If HttpContext.Current.Session("UserID") IsNot Nothing Then
    UserID = Guid.Parse(HttpContext.Current.Session("UserID").ToString())
End If

以防你感到困惑,请注意,除非我的记忆出现问题,否则Guid构造函数将生成一个“空”的guid。如果你想生成一个新的guid,请使用Guid.NewGuid()


我能否去掉 If 语句并使用 TryParse?这样会更有效吗? - Scott Selby
如果根据你的逻辑有意义,那么你应该去做。我不知道你是否需要处理TryParse返回false的情况。 - Claudio Redi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接