问题
I need to assign values to a two-dimensional array. I can do it using multiple "myArray[x,y]" statements but I'd like to use another method (because I'll have arrays with many lines/columns) - see code:
int x;
x = 1;
string[,] myArray = new string[2, 2];
if (x == 1)
{
//does not work : why? Would be easier to populate a big array using this
//myArray=
//{
// {"1", "1" },
// {"1", "1" }
//} ;
//works, but I need above code to work if possible
myArray[0, 0] = "1";
myArray[0, 1] = "1";
myArray[1, 0] = "1";
myArray[1, 1] = "1";
}
else if (x == 2)
//does not work
//myArray=
//{
//{"2", "2" },
//{"2", "2" }
//} ;
myArray[0, 0] = "2";
myArray[0, 1] = "2";
myArray[1, 0] = "2";
myArray[1, 1] = "2";
}
MessageBox.Show(myArray[0,0]);
thanks
回答1:
As you mentioned that you need to use it in that way, then you can do a workaround by declaring a temp variable initialize the values on it and then set the temp variable to the public one, like below:
int x;
x = 1;
string[,] myArray = new string[2, 2];
if (x == 1)
{
string[,] myArrayTemp = { {"1", "1" }, {"1", "1" } };
}
else if (x == 2)
{
string[,] myArrayTemp = { {"2", "2" }, {"2", "2" } };
myArray = myArrayTemp;
}
回答2:
I don't know if you are specifically looking to hardcode the values or not, but if you know the dimensions of the array to always be [2, 2]
you can loop across all values of x you need.
var totalEntries = 10;
for (var x = 1; x <= totalEntries; x++)
{
for (var i = 0; i < 2; i++)
{
for (var j = 0; j < 2; j++)
{
myArray[i, j] = x.toString("G");
}
}
}
回答3:
Why don't just:
if(x == 1 || x == 2) {
for(int row = 0; row < ROW_COUNT; row ++)
{
for(int col = 0; col < COL_COUNT; col++)
{
myArray[row, col] = x.ToString();
}
}
}
Not sure if if
condition matters in your case.
If you are asking about something else, please clarify.
回答4:
You should also consider using loops to populate a large array.
var size = 1;
for(int i = 0; i <= size; i++)
{
myArray[0, i] = x.ToString();
myArray[i, 0] = x.ToString();
}
回答5:
Referring to the other question you asked, simply try it this way:
int x;
x=1;
string[,] myArray;
switch (x)
{
case 1:
myArray = new string[,]{ { "1", "1" }, { "1", "1" } }; //OK
break;
case 2:
myArray = new string[,]{ { "2", "2" }, { "2", "2" } }; //OK
break;
}
You can't shorten these assignments, i.e.
myArray = { { "2", "2" }, { "2", "2" } };
is not allowed (syntax error), because in C# you always need the new
keyword to create a new object and a datatype which is string[,]
(for two-dimensional arrays) if don't want to specify the array sizes beforehand (you don't need to count the elements this way).
来源:https://stackoverflow.com/questions/27807824/c-sharp-error-creating-an-array