如何将枚举值保存到会话中
我正在创建枚举属性。该属性应保存到会话中。我的代码在这里
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;
}
}
编译器发布错误
return Session["Mode"] as TPageMode as 运算符必须与引用类型或可为 null 的类型一起使用
当我将此行替换为时
return Enum.Parse(typeof(TPageMode), Session["Mode"].ToString());
显示此错误
无法将类型“object”隐式转换为“TPageMode”
如何从中读取枚举值会议?
I'm creating enum property. This property should saved into session. My code is here
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;
}
}
compiler release error on return Session["Mode"] as TPageMode
The as operator must be used with a reference type or nullable type
When i replacing this row to
return Enum.Parse(typeof(TPageMode), Session["Mode"].ToString());
This error shown
Cannot implicit convert type 'object' to 'TPageMode'
How to read Enum value from session?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
正如错误消息所示,“as”不能与不可为空值类型一起使用。如果您随后转换为正确的类型,Enum.Parse 将会起作用(效率低下):
Try this:
As the error message says, "as" can't be used with non-nullable value types. Enum.Parse would have worked (inefficiently) if you'd then cast to the right type:
该代码
返回错误,因为
TPageMode
不是引用类型。as
运算符是 C# 中一种特殊的基于反射的类型转换。它检查运算符左侧是否可以转换为右侧的类型。如果转换不可能,则表达式返回 null。由于TPageMode
是一个枚举并且基于值类型,因此它不能保存 null 值。因此,此示例中不能使用该运算符。要执行此类型转换,只需使用
使用此语法,如果无法进行转换,则运行时会抛出
InvalidCastException
。当您确信在正常情况下始终可以进行转换时,请使用此语法。The code
returns an error, because
TPageMode
is not a reference type.The
as
operator is a special kind of reflection-based type conversion in C#. It checks whether the left-hand-side of operator can be converted to the type on the right-hand-side. If the conversion is not possible, the expression returns null. SinceTPageMode
is an enum and is based on value types, it cannot hold the value null. As such, the operator cannot be used in this example.To perform this type conversion, simply use
Using this syntax, if the conversion is not possible, an
InvalidCastException
is thrown by the runtime. Use this syntax when you are confident the conversion should always be possible in normal circumstances.