C#字符串数组返回错误的值

时间:2017-02-23 13:38:06

标签: c# arrays string

当我运行我的程序时,我从字符串数组中得到错误的值,我不知道为什么会这样...

我的代码:

BackGroundWorker bgw = new BackGroundWorker();
Form1_Load(object sender, EventArgs e)
{
    bgw.DoWork += delegate {
        Open();
    }
    bgw.RunWorkerAsync();
}
private void Open()
{
    string line = "put --------------------,true,10,0";

    var lineContent = line.Split(' ');
    var syx = lineContent[0];
    var cont = lineContent[1];
    var contents = cont.Split(',');

    if (syx == "put")
    {
        if (contents.Length == 4) // In Debug This Is True
        {
            // Debugger : contents[0] = "-------------------"
            //                    [1] = "true"
            //                    [2] = "10"
            //                    [3] = "0"
            string m = contents[0]; // m = " "
            string r = contents[1]; // r = "true"
            string s = contents[2]; // s = "1"
            string rnd = contents[3]; // rnd = "0"
        }
    }
}

正如您所看到的,我的contents数组具有正确的值但是当我尝试从我的数组中获取值时,它会给出错误或不完整的值 Debugger 我的代码错了吗?或其他什么?

2 个答案:

答案 0 :(得分:-1)

检查一下:

string[] lineContent = new string[] { };
string syx = "";
string cont = "";
string[] contents = new string[] { };
string er = "";

string line = "put --------------------,true,10,10";
lineContent = line.Split(' ');
syx = lineContent[0];
cont = lineContent[1];
contents = cont.Split(',');

if (syx == "put")
{
  if (contents.Length == 4) // In Debug This Is True
  {
    // Debugger : contents[0] = "-------------------"
    //                    [1] = "true"
    //                    [2] = "10"
    //                    [3] = "10"
    string m = contents[0]; // m = " "
    string r = contents[1]; // r = "true"
    string s = contents[2]; // s = "1"
    string rnd = contents[3]; // rnd = "0"
  }

}

答案 1 :(得分:-1)

通过使用不同的变量名来修复......不知道为什么,但这样我的问题就解决了。