2011-02-06 60 views
1
protected void Button2_Click(object sender, EventArgs e) 
    { 
     int[] L = { 1, 2, 3, 4, 5 }; 
     ViewState["I"] = L.ToArray(); 
    } 
protected void Button1_Click(object sender, EventArgs e) 
    { 
     int[] I = { }; 
     if (ViewState["I"] != null) 
      I = (int[])ViewState["I"]; 
     for (int i = 0; i < I.Length; i++) 
      Response.Write(I[i].ToString()); 
    } 

当我运行程序时,发生错误:如何将数组存储在asp.net中的ViewState中?

无法转换 类型的对象 'System.Collections.Generic.List`1 [System.Int32]' 为类型“系统。 INT32 []”。

为什么会发生此错误?

回答

1

删除.ToArray()调用。 L已经是int的一个数组(int []是一个数组构造函数)。你得到错误的原因是因为你正试图将它作为IList存储时返回给一个int数组。

所以要重申,只是不要打电话给.ToArray,你应该很好!

+0

嗨。我做到了,但没有奏效。 – vmahdavi 2011-02-06 18:09:05

4

ToArray()方法创建一个IEnumerable集合,即List。这不是一个int []。

我也建议只删除“ToArray()”扩展方法

+0

嗨。我做到了,但没有奏效。 – vmahdavi 2011-02-06 17:40:57