简体   繁体   English

如何处理int类型的会话变量中的null

[英]How to handle null in session variable of type int

If the session["Colindex"] is null. 如果session["Colindex"]为null。 It throws a error msg saying that Object reference not set to null. 它将引发错误消息,提示对象引用未设置为null。

int colid =(int) Session["ColIndex"];

Any help is appreciated 任何帮助表示赞赏

Use C# ?? 使用C# ?? null coalescing operator: 空合并运算符:

int colid = (int)(Session["ColIndex"] ?? 0);

This will set colid to the value in Session, or 0 if it's null. 这会将colid设置为Session中的值,如果为null,则设置为0。

If the Session["ColIndex"] has yet to be created, then there is no value. 如果尚未创建Session["ColIndex"] ,则没有任何值。 As Session is a reference variable, there is no reference to the instance of the object on the heap which is why you are receiving the " Object reference not set to an instance of an object " error. 由于Session是一个引用变量,因此没有对堆上对象实例的引用,这就是为什么您收到“ 对象引用未设置为对象实例 ”错误的原因。 In other words, the Session variable was never assigned/created. 换句话说,从未分配/创建Session变量。

You'll need to test for null before casting your session: 投放会话之前,您需要测试null:

if ( Session["ColIndex"] != null )
{
  int colid = (int)Session["ColIndex"];
  // do other stuff
}

我不知道这是什么语言,但是您可能需要在转换为int之前测试null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM