如何在运行时将字符串数组存储到单个应用程序设置 属性?

How can I store an array of strings at runtime to a single application settings property?

我想存储从应用程序内部保存的服务器名称的用户输入。我的 SettingsForm class 中的索引越界设置出现错误(错误行如下所示)。我相信我的 ServerName 属性 只有一个大小,所以我该如何改变它?或者我的代码中是否需要更改其他内容?

我不确定将多个字符串存储到一个 属性。我一直在尝试不同的事情,但我是 C# 和 WinForms 应用程序的新手。这是我一直在尝试计算的代码:

用户设置class:

[UserScopedSetting()]
    [DefaultSettingValue("Enter Server Name")]
    public String[] ServerName
    {
        get
        {
            return (String[])this["ServerName"];
        }
        set
        {
            this["ServerName"] = (String[])value;
        }
    }

设置表单class:

private void saveSettingsButton_Click(object sender, EventArgs e)
    {
        //loop through all servers
        for (int i=0; i<serverCounter.Value; i++)
        {
            TextBox currentTextBox = (TextBox)servers[i, 0];
            us.ServerName[i] = currentTextBox.Text; //ERROR
            currentTextBox.DataBindings.Add("Text", us, "ServerName");

        }
        us.Save();

        this.Close();
    }

潜在问题:serverCounter.Value有什么价值? us.ServerName[] 是如何实例化的? ServerName returns 是一个字符串数组,但在我看来每个serverName 应该是一个字符串,然后放入一个数组(或列表)中。

根据您显示的代码片段,我的猜测是 serverCounter 的某个值大于 1,并且 us.ServerName 始终是一个包含 1 个项目的数组(或者从未实例化)。这会给你一个索引超出范围的错误。

尝试使用 public string ServerName 而不是 public String[] ServerName,然后每次获得 return 值时,将该值放入数组中——或者如果您不知道有多少服务器会被输入,一个列表会更好

List<string> serverNames = new List<string>();

// Get currentName from user--I don't understand how your code is supposed to work

serverNames.Add(currentName);  // this is the name entered by the user

然后使用foreach循环:

        foreach (string name in serverNames)
        {
            //do something
        }

如果事先知道有多少台服务器,可以使用字符串数组:

string[] serverNames = new string[serverCounter];

并且仍然使用 foreach 循环对其进行迭代。