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

Sco*_*lby 4 vb.net asp.net casting guid

我有Guid"UserID",它需要填充Session("UserID"),这是一个String,但格式化为完美转换为Guid.

如果我试试这个,"无法将类型字符串转换为类型Guid"

       Dim UserID As New Guid()
       If HttpContext.Current.Session("UserID") IsNot Nothing Then
          UserID = HttpContext.Current.Session("UserID")
       End If
Run Code Online (Sandbox Code Playgroud)

如果我尝试这个"无法将类型字符串转换为类型Guid"

       Dim UserID As New Guid()
       If HttpContext.Current.Session("UserID") IsNot Nothing Then
          UserID = DirectCast(HttpContext.Current.Session("UserID"), Guid)
       End If
Run Code Online (Sandbox Code Playgroud)

这会将字符串完美地转换为Guid,但它不能在If语句之外访问

       If HttpContext.Current.Session("UserID") IsNot Nothing Then
         Dim UserID As new Guid(HttpContext.Current.Session("UserID"))
       End If
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何在If语句之外定义UserID,然后有条件地分配它

Cla*_*edi 9

试试这个

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

如果你感到困惑,请考虑到,除非我的记忆失败,Guid构造函数将生成一个"空"的guid.如果你想生成一个新的guid使用Guid.NewGuid()