如何在从会话列表中检索值时处理空值(how to handle null value in while retrieving values from session list)

编程入门 行业动态 更新时间:2024-10-27 15:29:23
如何在从会话列表中检索值时处理空值(how to handle null value in while retrieving values from session list)

我通过检索和分配会话中的值来在会话中存储多个值,如下所示:

var imageSessList = (List<string>)Session["ImagesNames"]; if (imageSessList != null) { string image1 = imageSessList[0]; string image2 = imageSessList[1]; string image3 = imageSessList[2]; string image4 = imageSessList[3]; }

但是如果会话只包含3个值,那么当分配string image4 = imageSessList[3]; 它会抛出null错误。

如何在这种情况下处理null。

I'm storing multiple values in session by retrieve & assign values from the session like this :

var imageSessList = (List<string>)Session["ImagesNames"]; if (imageSessList != null) { string image1 = imageSessList[0]; string image2 = imageSessList[1]; string image3 = imageSessList[2]; string image4 = imageSessList[3]; }

but what if the session contain only 3 values, so while assigning string image4 = imageSessList[3]; it throws null error.

how to handle null in such situation.

最满意答案

会话中的值可能为null,因此您必须在转换它们之前检查null。 所以初始条件是if (Session["ImagesNames"] != null)现在可以安全地转换它们并分配给imageSessList 。 因此变量imageSessList将包含会话变量中的项,并且您需要根据它们的索引获取这些项,然后在访问它们之前更好地检查该数组索引是否存在。 所以完整的代码将是这样的:

if (Session["ImagesNames"] != null) { var imageSessList = (List<string>)Session["ImagesNames"]; string image1 = imageSessList.Count>0? imageSessList[0]:""; string image2 = imageSessList.Count>1? imageSessList[1]:""; string image3 = imageSessList.Count>2? imageSessList[2]:""; string image4 = imageSessList.Count>3? imageSessList[3]:""; // Continue the job with these image variables // Variables will be "" if those values are not found in the list }

The value in the session may be null so you have to check for null before casting them. so the initial condition would be if (Session["ImagesNames"] != null) Now it is safe to cast them and assign to imageSessList. So the variable imageSessList will contains items in the session variable, and you needed to get those items based on their index, before accessing them its better to check for existence of that array index. So the complete code would be like this:

if (Session["ImagesNames"] != null) { var imageSessList = (List<string>)Session["ImagesNames"]; string image1 = imageSessList.Count>0? imageSessList[0]:""; string image2 = imageSessList.Count>1? imageSessList[1]:""; string image3 = imageSessList.Count>2? imageSessList[2]:""; string image4 = imageSessList.Count>3? imageSessList[3]:""; // Continue the job with these image variables // Variables will be "" if those values are not found in the list }

更多推荐

本文发布于:2023-08-06 20:02:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1455327.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   列表中   handle   null   list

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!