【问题标题】:saving arraylist in application settings winforms [duplicate]在应用程序设置winforms中保存arraylist [重复]
【发布时间】:2026-01-20 09:30:01
【问题描述】:

我正在编写一个简单的应用程序 - 一种用 C# 编写的 winforms 游戏。我的应用程序已经在应用程序设置中保存了一些信息,例如按钮的大小或颜色,但是当我尝试保存自己结构的数组列表时,我遇到了问题。没有错误,但信息不会保存以供下次程序执行。Ustawienia 是一个公共静态类,包括另一种形式的 wyniki,Properties.Settings.Default.scores 是在应用程序设置中添加的 ArrayList。如果您知道我做错了什么以及如何将数组列表存储在应用程序设置中,我将不胜感激。

代码如下:

公共部分类 Form3 : Form {

    public Form3()
    {
        InitializeComponent();
        if (Properties.Settings.Default.scores == null)
            Properties.Settings.Default.scores = new System.Collections.ArrayList();

    }

    private void ok_click(object sender, EventArgs e)
    {

       Highscore higscore = new Highscore(Properties.Settings.Default.ktory, textBox1.Text, ustawienia.ile_wierszy, ustawienia.ile_kolumn, ustawienia.elapsed.Seconds);
       Properties.Settings.Default.scores.Add( higscore);

       Properties.Settings.Default.scores.Sort(new myComparer());

       Properties.Settings.Default.ktory++;
       Properties.Settings.Default.Save();
       Highscore.show();
       this.Close();

    }

}
public class Highscore
{
   public int nubmer;//w properties ktory=+1;
   public string name;
    int rows;
    int columns;
   public int time;
    public Highscore(int _number, string _name, int _rows, int _columns, int _time)
    {
        number = _number;
        name = _name;
        rows = _rows;
        columns = _columns;
        time = _time;
    }
    public static void show()
    {
          ListView list = (ListView)ustawienia.wyniki.Controls.Find("listView1", true)[0];
          list.Items.Clear();
        foreach (Highscore e in Properties.Settings.Default.scores)
        {

            ListViewItem newItem = new ListViewItem(new[] { e.name, e.time.ToString(), e.rows.ToString()+"x"+e.columns.ToString() });
            lista.Items.Add(newItem);
        }

        ustawienia.wyniki.Show();
    }
}
public class myComparer:IComparer
{

int IComparer.Compare(Object x, Object y)
{
    if (((Highscore)x).time < ((Highscore)y).time)
        return 1;
    else if   (((Highscore)x).time > ((Highscore)y).time)
        return -1;
    else
    {

            return String.Compare(((Highscore)x).name,((Highscore)y).name);
    }
}
}

}

【问题讨论】:

    标签: c# winforms arraylist application-settings


    【解决方案1】:

    根据我的经验,尝试使用默认设置总是有问题。例如,在 Windows 8 上,默认设置保存在此文件夹模式中:

    C:\Users\[username]\AppData\Local\[AssemblyName]\[AssemblyName].exe_Url_[random_string_of_characters]\1.0.0.0\user.config

    但是,在调试模式下,它将是 .vhost.exe,然后在本地测试时,它将只是 .exe。然后如果版本增加它会再次改变路径。

    最终我放弃了试图找出正在使用的Settings 文件,并试图强制它保存到不同的(更干净的)文件夹。相反,我改用自定义设置类并使用XmlSerializer。这不值得头疼。

    【讨论】: