2012-07-10 89 views
1

我有Guid“UserID”,它需要填充Session(“UserID”),它是一个字符串,但格式化为完全转换为Guid。在VB.Net中将字符串转换为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 

我不明白如何t ○定义用户名和IF语句的外面,然后将其指定有条件

回答

6

与此

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.NewGuid()

+0

我可以拿出If语句并使用TryParse? ,那会更有效率吗? – 2012-07-10 02:38:52

+0

@ScottSelby:如果根据你的逻辑理解,那么你应该去做。我不知道你是否需要处理'TryParse'返回false的情况 – 2012-07-10 02:41:18