【问题标题】:How can I store an array in a ViewState in asp.net?如何将数组存储在 asp.net 的 ViewState 中?
【发布时间】:2011-02-06 16:16:18
【问题描述】:
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());
    }

当我运行程序时,出现错误:

无法转换类型的对象 'System.Collections.Generic.List`1[System.Int32]' 输入“System.Int32[]”。

为什么会出现这个错误?

【问题讨论】:

    标签: c# asp.net viewstate


    【解决方案1】:

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

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

    【讨论】:

    • 嗯.. 很奇怪.. 我刚刚创建了一个新的 asp.net 项目,代码工作得很好:/
    • 这真的很奇怪吗?现在一切正常吗?
    【解决方案2】:

    删除 .ToArray() 调用。 L 已经是一个 int 数组(int[] 是一个数组构造函数)。您收到错误的原因是因为您在将其存储为 IList 时试图将其转换回 int 数组。

    所以重申一下,只要不要调用 .ToArray 就可以了!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-08
      • 1970-01-01
      相关资源
      最近更新 更多