C#错误创建数组 [英] C# error creating an array

查看:115
本文介绍了C#错误创建数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将值分配到一个二维阵列。
我可以用它的多个myArray的[X,Y]的语句,但我想用另外一种方法(因为我将有许多行/列阵列)做的 - 见code:

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

感谢

推荐答案

临时变量给公众的,象下面这样:

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;    
}

这篇关于C#错误创建数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆