我使用按钮将数组添加到数组中,并给出了错误
我想在数组中包含带有按钮的数组,我可以输出它们,但它给出了错误
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];
}
}
答案 0 :(得分:1)
初始化数组的方式是错误的,这就是初始化12个按钮的数组的方式
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()
}
}
或更简洁
Button[] Months = new Button[12];
for(int i =0; i<12; i++)
Months[i] = new Button();
如果您希望每个月都能访问一个命名成员的按钮,则可以为每个成员创建一个属性:
public Button January => Months[0];
public Button February=> Months[1];
//etc
虽然还不清楚您想要什么。如果您想要一个由32个按钮组成的12个数组,则可以这样初始化:
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();
}
如果您热衷于单行处理,可以这样完成:
Months = Enumerable.Range(0, 12)
.Select(e =>
Enumerable.Range(0, 32)
.Select(f => new Button()).ToArray())
.ToArray();
答案 1 :(得分:1)
通过@ tim-rutter扩展出色的答案:
使用Dictionary可以最好地实现我想做的事情。字典允许您指定唯一键(在本例中为Month)并将其与值(在本例中为按钮数组)关联。
简单实现:
class CalendarBase
{
public Dictionary<string, Button[]> Month = new Dictionary<string, Button[]>()
{
{"January", new Button[32] },
{"February", new Button[32] },
{"March", new Button[32] },
{"April", new Button[32] },
{"May", new Button[32] },
{"June", new Button[32] },
{"July", new Button[32] },
{"August", new Button[32] },
{"September", new Button[32] },
{"October", new Button[32] },
{"November", new Button[32] },
{"December", new Button[32] },
};
}
然后,您可以像访问数组一样访问每个按钮数组:
var februaryButtons = Month["February"];
更好的实现是将Enum用作键,这样您就不必担心在尝试访问值时字符串的拼写错误会引发异常。
更好:
enum Months
{
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
}
class CalendarBase
{
public Dictionary<string, Button[]> Month = new Dictionary<string, Button[]>()
{
{Months.January, new Button[32] },
{Months.February, new Button[32] },
{Months.March, new Button[32] },
{Months.April, new Button[32] },
{Months.May, new Button[32] },
{Months.June, new Button[32] },
{Months.July, new Button[32] },
{Months.August, new Button[32] },
{Months.September, new Button[32] },
{Months.October, new Button[32] },
{Months.November, new Button[32] },
{Months.December, new Button[32] },
};
}
然后,您可以像这样访问每个按钮阵列:
var februaryButtons = Month[Months.February];