VB.Net Session变量简写方案分享:简化繁琐Session操作
VB.Net Session变量操作简化方案
分享个我自己写的简写函数,用来简化VB.Net里Session变量的操作,省得每次都写一大串Session相关代码。
原来的繁琐写法
之前操作Session变量得这么写:
Session("NameOfSomething") = "Bob" Label1.Text = Session("NameOfSomething") Session.Remove("NameOfSomething")
简化后的写法
用了简写函数之后,代码清爽多了:
s("NameOfSomething", "Bob") Label1.Text = s("NameOfSomething") sr("NameOfSomething")
实现代码
把下面的函数放到项目的公共模块里就能用:
' 用于赋值或获取Session变量 Function s(key As String, Optional value As Object = Nothing) As Object If value IsNot Nothing Then Session(key) = value End If Return Session(key) End Function ' 用于删除Session变量 Sub sr(key As String) Session.Remove(key) End Sub
注:如果在Web Forms页面外使用,需要确保代码能通过
HttpContext.Current.Session访问到Session对象。
内容的提问来源于stack exchange,提问作者Kevin
相关产品推荐
相关产品推荐

