[英]Why do I need to typecast Viewstate Variables in asp.net
I am a beginner in asp.net and I have encountered these following statements 我是asp.net的初学者,遇到以下这些陈述
Statement 1 陈述1
ViewState["clicks"] = 5;
Statement 2 陈述2
ViewState["clicks"] = (int)ViewState["clicks"] + 1;
My doubt is If I am able to directly assign int value...Why do I need to typecast when I am incrementing the value in viewstate variable? 我的疑问是,如果我能够直接分配int值...为什么在增加viewstate变量中的值时需要进行类型转换? Thanks in advance....... 提前致谢.......
ViewState["clicks"]
returns an object
. ViewState["clicks"]
返回一个object
。 You can't use the +
-operator (addition) on Object
. 您不能在Object
上使用+
运算符 (加法)。 Therefore you need to cast the object to it's real type int
. 因此,您需要将对象强制转换为实型int
。 Then it compiles. 然后编译。
The right side is evaluated first and assigned back to the ViewState
. 首先评估右侧,然后将其分配回ViewState
。 Maybe it's getting clearer if you make it multiple lines: 如果将其设置为多行,可能会变得更加清晰:
int oldClicks = (int)ViewState["clicks"];
int newClicks = oldClicks + 1;
ViewState["clicks"] = newClicks;
因为ViewState[]
将返回object类型的object
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.