ASP.net如何使用会话?
我需要将我的变量分配给会话。我尝试过这个:
string name = string.Empty
Session["N"] = name;
但行不通。
Error 1 Invalid token '[' in class, struct, or interface member declaration
Error 2 Invalid token '"N"' in class, struct, or interface member declaration
Error 3 Identifier expected
我哪里错了?
我在 Visual Studio 2008 中使用 ASP.net。
错误 1 类、结构或接口成员声明中的标记“[”无效 错误 2 类、结构或接口成员声明中的标记“N”无效
错误 3 需要标识符
I need to assign my variable to session. I tried this:
string name = string.Empty
Session["N"] = name;
and it won't work.
Error 1 Invalid token '[' in class, struct, or interface member declaration
Error 2 Invalid token '"N"' in class, struct, or interface member declaration
Error 3 Identifier expected
Where I'm wrong?
I'm using ASP.net in Visual Studio 2008.
Error 1 Invalid token '[' in class, struct, or interface member declaration
Error 2 Invalid token '"N"' in class, struct, or interface member declaration
Error 3 Identifier expected
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一行末尾缺少
;
。missing
;
end of first line.该代码没有任何问题(除了缺少分号,正如 Shree Khanal 指出的那样,但这不可能是问题,对吧?)。
只要代码位于页面类中,
Session
属性就可用。如果您的代码位于不同的类中,则没有可用的Session
属性,那么您需要从当前上下文中获取它:从会话集合中读取值时,类型为
Object
,而不是String
,因此您需要对其进行强制转换:使用
as
关键字意味着您可以尝试读取该值,即使它会不存在,或者恰好被设置为不同的数据类型。在这种情况下,您将得到一个null
引用。There is nothing wrong with that code (except a missing semicolon, as Shree Khanal pointed out, but that can't be the issue, right?).
As long as the code is in the page class, the
Session
property is available. If you have the code in a different class, you don't have theSession
property available, then you need to get it from the current context:When reading the value from the session collection, the type is
Object
, notString
, so you need to cast it:Using the
as
keyword means that you can attempt to read the value even if it would not exist, or if it happens to be set to a different data type. In that case you will get anull
reference back.