c# - 如何在 C# 中将空 session 值默认为空白字符串

标签 c# asp.net session session-variables

我习惯使用 VB.net 进行网络编程。

通常,我有这样的事情:

Dim s as string = Session("s")

我从网络 session 中获取了 s 的字符串值。如果网络 session 中没有值,我会得到一个空字符串。

但是,据我所知,在 C# 中,我必须有类似于下面的代码才能做同样的事情。

string s;
try { s = Session["s"].ToString(); }
catch { s = ""; }

有更简单的方法吗?

最佳答案

这是一种快速的方法:

s = (string)Session["s"] ?? "";

这会将 Session["s"] 转换为字符串,如果不为空,则返回该值。如果为空,它将返回一个空字符串。 “a ?? b”表达式本质上与“a != null ? a:b”相同(?? 编译得更多虽然有效)

还有一点要记住:您永远不应该对正常的应用程序逻辑使用异常。

关于c# - 如何在 C# 中将空 session 值默认为空白字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3981787/

相关文章:

asp.net - 发送 IEnumerable<T> 时对 EditorTemplate 进行客户端不显眼的验证

asp.net - https 请求在 Windows Azure 中不起作用

php - 将 Session 变量从 Ajax 发送到 PHP

http - session 、HTTP 连接之间的区别?

c# - AzureWebJobs仪表板配置错误

c# - ASP.NET C# + Nhibernate HTTP 模块 (Session per request) - 限制请求类型

c# - 在 C# 中使用 xpath,帮助

c# - 带 HTTP 2.0 的 RestSharp

google-app-engine - 是否可以在谷歌应用引擎上将马提尼的 sessionauth 与数据存储一起使用?

c# - 插入、更新、删除记录时返回记录的id