You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# 如何将存储Dictionary<string,string>的ArrayList显式转换为对应类型数组

问题根因

ArrayList是.NET Framework早期提供的非泛型集合类,所有存入的元素都会被装箱为object类型,无参ToArray()方法返回的是object?[],和你需要的强类型Dictionary<string, string>[]不兼容。你之前几次报错都是因为ToArray()的泛型重载参数传值错误:该方法需要接收Type类型的参数,而非直接写类型名。

可用解决方案

方案1:使用ArrayList自带的带参数ToArray方法

无需引入额外命名空间,直接指定转换的目标类型即可:

Dictionary<string, string>[] profiles = (Dictionary<string, string>[])settings.ToArray(typeof(Dictionary<string, string>));

方案2:使用LINQ的Cast方法(更简洁)

先引入LINQ命名空间:

using System.Linq;

再执行转换:

Dictionary<string, string>[] profiles = settings.Cast<Dictionary<string, string>>().ToArray();

现有代码隐藏问题修复

你当前的getSettingsOf方法存在逻辑bug:temp字典是在while(reader.Read())循环外定义的,第一次循环添加键值对正常,第二次循环会因为重复添加相同的键抛出异常。需要把字典的实例化移到循环内部:

public ArrayList getSettingsOf(string name)
{
    SQLiteConnection m_dbConnection = PullDB();
    // 注意:这里的SQL拼接存在SQL注入风险,建议改成参数化查询
    string sql = String.Format("select * from Settings where Name = {0}", name);
    SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
    SQLiteDataReader reader = command.ExecuteReader();
    ArrayList output = new ArrayList();
    while (reader.Read())
    {
        // 每次读取一行就新建一个字典
        Dictionary<string, string> temp = new Dictionary<string, string>();
        temp.Add("Foo1", reader["Bar1"].ToString());
        temp.Add("Foo2", reader["Bar2"].ToString());
        temp.Add("Foo3", reader["Bar3"].ToString());
        temp.Add("Foo4", reader["Bar4"].ToString());
        temp.Add("Foo5", reader["Bar5"].ToString());
        output.Add(temp);
    }
    return output;
}

额外提示:现有SQL用字符串拼接的写法存在SQL注入风险,建议改为参数化查询写法。

优化建议

不推荐继续使用ArrayList,可以直接将方法返回值改为泛型集合List<Dictionary<string, string>>,既保证类型安全,也无需后续做类型转换:

public List<Dictionary<string, string>> getSettingsOf(string name)
{
    SQLiteConnection m_dbConnection = PullDB();
    string sql = "select * from Settings where Name = @Name";
    SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
    command.Parameters.AddWithValue("@Name", name);
    SQLiteDataReader reader = command.ExecuteReader();
    List<Dictionary<string, string>> output = new List<Dictionary<string, string>>();
    while (reader.Read())
    {
        Dictionary<string, string> temp = new Dictionary<string, string>();
        temp.Add("Foo1", reader["Bar1"].ToString());
        temp.Add("Foo2", reader["Bar2"].ToString());
        temp.Add("Foo3", reader["Bar3"].ToString());
        temp.Add("Foo4", reader["Bar4"].ToString());
        temp.Add("Foo5", reader["Bar5"].ToString());
        output.Add(temp);
    }
    return output;
}

调用时直接转数组即可:

Dictionary<string, string>[] profiles = getSettingsOf("xxx").ToArray();

内容的提问来源于stack exchange,提问作者derwookie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 07:51:02