将布尔值转换为会话变量

时间:2013-11-10 16:47:58

标签: c# asp.net visual-studio-2010 boolean session-variables

关于如何将代码中的“可食用”转换为会话以在不同页面上显示为标签的任何想法。 将非常感谢帮助。

标签会显示“是可以吃”的消息

代码吼叫

public int totalCalories()
        {
            return grams * calsPerGram;
        }
        public string getFruitInfo()
        {
            string s;
            if (edible == true)
            {
                s = fName + " is good and it has " + totalCalories() +
 "calories";
            }
            else
            {
                s = "Hands off! Not edible";
                //edible = Sesion ["ediblesesion"] as bool;
                // Session ["ediblesession"] = edible;
            }
            return s;
        }
    }

3 个答案:

答案 0 :(得分:16)

您已经拥有了在if语句中的注释中设置会话变量的代码:

Session["ediblesession"] = edible;

但是,您可能希望将会话变量设置在之外的if语句中,这样即使布尔值为true,它也会获得一个值。

如果要在其他页面中读回值,您将获得一个对象中的布尔值,因此您需要将其强制转换为布尔值:

edible = (bool)Session["ediblesession"];

小心拼写。如果您尝试读取名为"ediblesesion"的会话变量(如注释中的代码所示),则不会获得存储为"ediblesession"的变量,并且编译器无法分辨你发了一个拼写错误,因为它不是标识符。

如果您想要读取该值,但可能在没有先设置值的情况下访问该页面,则需要检查它是否存在:

object value = Session["ediblesession"];
if (value != null) {
  edible = (bool)value;
} else {
  edible = false; // or whatever you want to do if there is no value
}

答案 1 :(得分:4)

环境:

this.Session["Edible"] = myBoolean;

获得:

myBoolean = (bool) this.Session["Edible"];

答案 2 :(得分:0)

bool? edible;
object object_edible = Session["session_edible"];
if (object_edible != null)
    edible = object_edible  as bool?;
else
    edible = false;

'布尔'是c#中的一个不可为空的值类型,bool?是一个可以为空的类型

相关问题