关于c#:变量未声明或从未分配,重建不起作用

The variable is either undeclared or was never assigned and rebuilding does not work

我有很多在MS论坛上反复被问到的问题-我有一个组合框控件和一个字符串数组,所以我在

表单1.designer.cs

1
2
3
4
5
6
private void InitializeComponent()
{
...
this.ComboBox_Target_0.Items.AddRange(Ranks);
...
}

数组本身的声明如下:

1
string[] Ranks = {"Rank 1","Rank 2","Rank 3","Rank 4","Rank 5","Rank 6","Rank 7","Rank 8","Rank 9","Rank 10","Rank 11","Rank 12" };

如果我构建我的解决方案,那么表单运行良好,组合框中列出了所有项,并且工作正常。但是表单设计器拒绝开始说"变量列组未声明或从未分配"。

我已经看到了关于这个问题的其他问题,并且已经尝试了他们(唯一)的解决方案-重建解决方案,关闭vs并打开它备份。但那没有帮助。我每次都尝试将字符串数组放入"initializecomponent()"和"public form1()",重新构建等等。然而,它并没有为我固定下来。

让我检查一下-在这种情况下选择"忽略并继续"不会危害任何东西,对吗?


我同意您不应该修改设计器文件。如果您在设计时需要这些值,并且您不想使用编辑器,那么我让它正常工作的唯一方法就是将它放在InitializeComponent方法的最上面:

1
string[] Ranks = new string[] {"Rank 1","Rank 2","Rank 3","Rank 4","Rank 5","Rank 6","Rank 7","Rank 8","Rank 9","Rank 10","Rank 11","Rank 12" };

我在声明中加了new string[]。这取决于编辑器在设计时创建列表的方式:

1
this.ComboBox_Target_0.Items.AddRange(new object[] {...

在这样定义了EDOCX1[2]之后,您的行将工作:

1
this.ComboBox_Target_0.Items.AddRange(Ranks);

如果您在运行时只需要这些值,那么最好这样做(或其变体):

1
2
3
4
5
6
7
8
9
10
public partial class Form1 : Form
{
    string[] Ranks = {"Rank 1","Rank 2","Rank 3","Rank 4","Rank 5","Rank 6","Rank 7","Rank 8","Rank 9","Rank 10","Rank 11","Rank 12" };

    public Form1()
    {
        InitializeComponent();
        this.ComboBox_Target_0.Items.AddRange(Ranks);
    }
}