玩转C科技.NET

从学会做人开始认识这个世界!http://volnet.github.io

导航

从ArrayList和ViewState之间得出的××!

晚上在瞎搞着代码,不知所谓地随便搞,拿ArrayList来存储int值,并用ViewState来缓存,以免因为页面内刷新而导致数据丢失。但是突然发现自己的代码在将数据取出到ArrayList后并对其做出修改(Add一个新的值)之后,忘记将其重新存回ViewState了,但是数据却始终保持着改变。发现之后赶快写了个例子程序,发现问题确实是ArrayList和ViewState之间所导致的,例子程序如下:

int increment = 1;
if (this.ViewState["myArray"== null)
{
    
this.ViewState["myArray"= new ArrayList();
}

ArrayList tempArray 
= (ArrayList)this.ViewState["myArray"];
tempArray.Add(increment);
//this.ViewState["myArray"] = tempArray;  //没有这句也可以!!!
int total = 0;
foreach (object item in tempArray)
{
    total 
+= int.Parse(item.ToString());
}

Response.Write(total.ToString()); 

现在程序会不断地增加数值,但注意这里除了this.ViewState["myArray"] == null的时候有将其加进ViewState之外,没有地方再对其缓存了。而每次都会通过(ArrayList)this.ViewState["myArray"]获取ViewState中的值,每次对tempArray的改变事实上在ViewState中已经有所反应了。

但是int类型则不会:

if (this.ViewState["myInt"== null)
{
    
this.ViewState["myInt"= 0;
}

int tempVal = (int)this.ViewState["myInt"];
tempVal
++;
this.ViewState["myInt"= tempVal; //没有这句就无法更新ViewState中的数据
Response.Write(tempVal.ToString()); 

每次显示都只会是同一个值,total++的变化并没有反映到结果中。

会不会是值类型和引用类型的区别呢?用string做个实验:

if (this.ViewState["myString"== null)
{
    
this.ViewState["myString"= "First ";
}

string tempVal = (string)this.ViewState["myString"];
tempVal 
= tempVal + " Value";
//this.ViewState["myString"] = tempVal; //没有这句就无法更新ViewState中的数据
Response.Write(tempVal); 

得到的答案和int是一样的。 (关于string的问题可以参看你真的了解.NET中的String吗?http://terrylee.cnblogs.com/archive/2005/12/26/304876.html

            //The Same as ArrayList
            if (this.ViewState["myStringBuilder"== null)
            
{
                
this.ViewState["myStringBuilder"= new System.Text.StringBuilder("First");
            }

            System.Text.StringBuilder sb 
= (System.Text.StringBuilder)this.ViewState["myStringBuilder"];
            sb.Append(
"Value");
            Response.Write(sb.ToString());

用StringBuilder后,再使用Append,又能出现和ArrayList的同样效果了。

结论:等号右边的项提供了对象的实际地址,如“ = (System.Text.StringBuilder)this.ViewState["myStringBuilder"];”只要对象的地址在操作中没有发生变化,那么该操作将反映到ViewState中。

posted on 2007-06-17 03:24  volnet(可以叫我大V)  阅读(1822)  评论(9编辑  收藏  举报

使用Live Messenger联系我
关闭