简体   繁体   中英

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

Statement 1

ViewState["clicks"] = 5;

Statement 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? Thanks in advance.......

ViewState["clicks"] returns an object . You can't use the + -operator (addition) on Object . Therefore you need to cast the object to it's real type int . Then it compiles.

The right side is evaluated first and assigned back to the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM