C# 访问 for 循环外部的数组

本文关键字:数组 外部 循环 访问 for | 更新日期: 2023-09-27 18:19:06

我想知道如何访问forloop之外的数组。

    string[] lines = File.ReadAllLines("Customers/" + listBox1.SelectedItem.ToString() + "/" + listBox1.SelectedItem.ToString() + ".txt");

         for (int i = 0; i < 4; i++)
         {
             string[] linesSplitted = lines[i].Split(':');
         }
         TextboxName.Text = linesSplitted[0];
         TextboxAddress.Text = linesSplitted[1];
         TextboxZip.Text = linesSplitted[2];
         TextboxTel.Text = linesSplitted[3];
         TextboxEmail.Text = linesSplitted[4];

此时,它无法识别行拆分。

C# 访问 for 循环外部的数组

从您对另一个答案的评论中,我想您想要这个:

string[] linesSplitted = new string[5];
for (int i = 0; i < 5; i++)
{
    linesSplitted[i] = lines[i].Split(':')[1];
}

如果这不是您想要的,请给我们一个文本文件内容的示例。

在循环之外声明数组。 例如

string[] lines = File.ReadAllLines("Customers/" + listBox1.SelectedItem.ToString() + "/" + listBox1.SelectedItem.ToString() + ".txt");
string[] linesSplitted;
for (int i = 0; i < 4; i++)
{
   linesSplitted = lines[i].Split(':');
}
TextboxName.Text = linesSplitted[0];
TextboxAddress.Text = linesSplitted[1];
TextboxZip.Text = linesSplitted[2];
TextboxTel.Text = linesSplitted[3];
TextboxEmail.Text = linesSplitted[4];
string[] lines = File.ReadAllLines("Customers/" + listBox1.SelectedItem.ToString() + "/" + listBox1.SelectedItem.ToString() + ".txt");

     string[] linesSplitted;
     for (int i = 0; i < 4; i++)
     {
         linesSplitted = lines[i].Split(':');
     }
     TextboxName.Text = linesSplitted[0];
     TextboxAddress.Text = linesSplitted[1];
     TextboxZip.Text = linesSplitted[2];
     TextboxTel.Text = linesSplitted[3];
     TextboxEmail.Text = linesSplitted[4];

我不确定你想在那里实现什么......

string[] lines = File.ReadAllLines("Customers/" + listBox1.SelectedItem.ToString() + "/" + listBox1.SelectedItem.ToString() + ".txt");

 List<string[]> data  = new List<string[]>(); 
         for (int i = 0; i < 4; i++)
         {
            data.Add(lines[i].Split(':'));
         }
//Retrive array from list and value from array and set to text box
         TextboxName.Text = linesSplitted[0];
         TextboxAddress.Text = linesSplitted[1];
         TextboxZip.Text = linesSplitted[2];
         TextboxTel.Text = linesSplitted[3];
         TextboxEmail.Text = linesSplitted[4];