eba*_*lga 4 c# asp.net session enums
我正在创建枚举属性.此属性应保存到会话中.我的代码在这里
public enum TPageMode { Edit=1,View=2,Custom=3}
protected TPageMode Mode {
get{
if (Session["Mode"] == null)
return TPageMode.Edit;
else
{
return Session["Mode"] as TPageMode; // This row is problem
}
}
set {
Session["Mode"] = value;
}
}
Run Code Online (Sandbox Code Playgroud)
编译器发布错误 return Session["Mode"] as TPageMode
The as operator must be used with a reference type or nullable type
当我将此行替换为
return Enum.Parse(typeof(TPageMode), Session["Mode"].ToString());
Run Code Online (Sandbox Code Playgroud)
显示此错误
Cannot implicit convert type 'object' to 'TPageMode'
如何从会话中读取枚举值?
试试这个:
return (TPageMode) Session["Mode"];
Run Code Online (Sandbox Code Playgroud)
如错误消息所示,"as"不能与非可空值类型一起使用.如果你然后转换为正确的类型,Enum.Parse 会工作(效率低下):
return (TPageMode) Enum.Parse(Session["Mode"], typeof(TPageMode));
Run Code Online (Sandbox Code Playgroud)