首页 > 解决方案 > 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];
    }
}

标签: c#

解决方案


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();

推荐阅读