将布尔值转换为会话变量

Bee*_*eep 10 c# asp.net boolean session-variables visual-studio-2010

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

标签将显示消息,如是可以吃

代码吼叫

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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

Guf*_*ffa 16

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

Session["ediblesession"] = edible;
Run Code Online (Sandbox Code Playgroud)

但是,您可能希望在语句外部设置会话变量if,以便即使布尔值为,也会获取值true.

当你想在另一个页面中读取值时,你将得到一个对象中的布尔值,所以你需要将它强制转换为一个布尔值:

edible = (bool)Session["ediblesession"];
Run Code Online (Sandbox Code Playgroud)

注意拼写.如果您尝试使用名称读取会话变量"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
}
Run Code Online (Sandbox Code Playgroud)