有人可以解释为什么下面的“ board”初始化不起作用吗?这是我的代码:
public partial class frmSudoku : Form
{
Label[,] board;
public frmSudoku()
{
InitializeComponent();
board = {{lblS00, lblS01, lblS02, lblS03, lblS04, lblS05, lblS06, lblS07, lblS08},
{lblS10, lblS11, lblS12, lblS13, lblS14, lblS15,lblS16,lblS17, lblS18},
{lblS20, lblS21, lblS22, lblS22, lblS24, lblS25, lblS26, lblS27, lblS28},
{lblS30, lblS31, lblS32, lblS33, lblS34, lblS35, lblS36, lblS37, lblS38},
{lblS40, lblS41, lblS42, lblS43, lblS44, lblS45, lblS46, lblS47, lblS48},
{lblS50, lblS51, lblS52, lblS53, lblS54, lblS55, lblS56, lblS57, lblS58},
{lblS60, lblS61, lblS62, lblS63, lblS64, lblS65, lblS66, lblS67, lblS68},
{lblS70, lblS71, lblS72, lblS73, lblS74, lblS75, lblS76, lblS77, lblS78},
{lblS80, lblS81, lblS82, lblS83, lblS84, lblS85, lblS86, lblS87, lblS88}};
}
我在VS2019上,每个逗号下都有那些红色下划线-它们的错误消息只是“;预期”(这显然是不对的;我试图用分号代替它只是为了查看,并且红色下划线刚刚转移了在带有错误消息“仅分配,调用,减量...可以用作语句”的标签下)。我真的不知道为什么这是非法的-我尝试在公共局部类下声明2D int数组,并在frmSudoku()中类似地对其进行初始化,并且效果很好。什么使标签数组与众不同?
编辑:2D int数组不能正常工作,红色下划线显示(哎呀)只用了一段时间。
答案 0 :(得分:9)
这不是2D阵列所独有的。使用ECMA C# Standard中的术语,数组初始化器仅在 array-creation-expression ,字段声明或局部变量声明中有效。
例如,这是有效的:
// array-initializer as part of a local variable declaration
string[] strings = { "x", "y" };
但这不是:
string[] strings;
// This is just an assignment expression, not part of a variable declaration
strings = { "x", "y" };
您可以使用* array-creation-expression(尽管:
string[] strings;
strings = new string[] { "x", "y" };
等效项适用于您的二维示例:
board = new Label[,] {{ ... }};