c# - When i added buttons in array. I got an error " An array initializer of length "12" is required"
问题描述
I added to the array with buttons, in the array and gave an error
I wanted to have arrays with buttons in the array and I could output them but it gave an error
class CalendarBase
{
public Button[] Mounth = new Button[12]
{
public Button[] January = new Button[32];
public Button[] February = new Button[32];
public Button[] March = new Button[32];
public Button[] April = new Button[32];
public Button[] May = new Button[32];
public Button[] June = new Button[32];
public Button[] July = new Button[32];
public Button[] August = new Button[32];
public Button[] September = new Button[32];
public Button[] November = new Button[32];
public Button[] December = new Button[32];
}
}
解决方案
The way you are initialising the array is wrong, this is how you would initialise a array of 12 buttons
class CalendarBase
{
public Button[] Months = new Button[12]
{
new Button(),
new Button(),
new Button(),
new Button(),
new Button(),
new Button(),
new Button(),
new Button(),
new Button(),
new Button(),
new Button(),
new Button()
}
}
Or more succinctly
Button[] Months = new Button[12];
for(int i =0; i<12; i++)
Months[i] = new Button();
If you want to be able to access the buttons by a named member for each month you could create a property for each:
public Button January => Months[0];
public Button February=> Months[1];
//etc
Its not completely clear what you want though. If you want an array of 12 arrays of 32 buttons, it would be initialised like this:
Button[][] Months = new Button[12][];
for (int i = 0; i < 12; i++)
{
Months[i]= new Button[32];
for (int j = 0; j < 32; j++)
Months[i][j] = new Button();
}
which if you're a fan of doing things in one line can be done like this:
Months = Enumerable.Range(0, 12)
.Select(e =>
Enumerable.Range(0, 32)
.Select(f => new Button()).ToArray())
.ToArray();
推荐阅读
- javascript - 最接近纯javascript中的试剂光标的东西
- python - Pyshark packet.tcp.analysis_ack_rtt 不始终可用
- plsqldeveloper - 使用 PL/SQL Developer 调试 PL/SQL 集合
- python - For 循环迭代似乎跳过了列表中的两个数字
- flutter - 如何修复制作空白的列并忽略我在颤动中的线性渐变
- docker - Docker:Java 运行时环境内存不足,无法继续
- django - 如何使用 PythonAnywhere SFTP 存储上传的文件以在 Django Filer 中超越文件大小限制?
- python - 有没有办法防止在 python 命令行上自动换行?
- angularjs - Docker:找不到本地咕噜声
- typescript - 错误 TS2339 TS 属性不存在。我正在做一些功课并遇到了这个问题。谁能回答为什么会发生这个错误?