0

我正在使用 Visual Studio 2010 开发一个 winform 项目。我注意到在创建包含对 Button (或任何其他 winform 控件)的引用的数组时会发生这种情况。如果我这样写:

Button[] buttonArray;
buttonArray = {Button1, Button2};

我会收到多个错误,例如Only assignment, call, increment, decrement, and new object expressions can be used as a statementInvalid expression term '{'仅举几例。

供您参考,Button1 和 Button2 在表单上。

即使我这样做,我仍然会遇到同样的错误:

Button[] buttonArray = new Button[2];
buttonArray = { Button1, Button2};

但是,如果我这样做,它会被 Visual Studio 接受:

Button[] buttonArray = new Button[2];
buttonArray[0] = Button1;
buttonArray[1] = Button2;

那么谁能告诉我出了什么问题?我认为包含对控件的引用的数组与字符串数组具有相同的本质。

谢谢你。

4

3 回答 3

4

当你这样做时:

Button[] buttonArray;
buttonArray = {Button1, Button2};

你没有使用array initialization语法。您正在做的是声明一个按钮数组但不实例化它,然后尝试将其分配给buttonArray代码块。数组初始化语法在赋值之外无效。就像是

void MyMethod()
{
    string[] s;
    { 
        int i = 0; 
    }
}

是 C# 中的有效代码块;方法内的卷曲只是改变范围。您无法将代码块分配给变量,例如这种情况:

void MyMethod()
{
    string[] s;
    s = 
    {
        int i = 0; 
    }; //Totally INVALID!
}

您需要结合声明和初始化,或new向上排列数组。

Button[] buttonArray = { Button1, Button2 }; //Valid

Button[] buttonArray;
buttonArray = new Button[] { Button1, Button2 }; //Also valid!
于 2013-08-22T03:50:43.210 回答
3

Try to use array initialization syntax

Button[] buttonArray = new [] { Button1, Button2 };

or

Button[] buttonArray;
buttonArray = new [] { Button1, Button2};

you can also substitute Button[] with var in the first example, since C# compiler is smart enough to infer types from initialization part.

Arrays can also be initialized without using new [] near variable declaration. In your case it would be

Button[] buttonArray = { Button1, Button2 };

But note, that you can't use var keyword, when you use such syntax. So next code is illegal:

var buttonArray = { Button1, Button2 }; //won't compile
于 2013-08-22T03:41:08.677 回答
1

Correct array initialization syntax is defined here : http://msdn.microsoft.com/en-us/library/aa287601(v=VS.71).aspx

于 2013-08-22T03:41:50.953 回答