我通过检索和分配会话中的值来在会话中存储多个值,如下所示:
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 }更多推荐
发布评论