You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 19:50:55