【问题标题】:Using variable outside of the for loop在 for 循环之外使用变量
【发布时间】:2018-09-28 14:19:06
【问题描述】:

我有一个问题:

public void button20_Click(object sender, EventArgs e)
{
    string CellDataID;
    string[] IDString;
    for (int RowCount = 2; RowCount <= LastRow; RowCount++)
    {
        xlRange = (Excel.Range)xlSht.Cells[RowCount, colNumberID];
        CellDataID = (string)xlRange.Text;
        PrinterBox1.Items.Add(CellDataID);
        IDString = new string[LastRow];
        IDString[RowCount - 1] = CellDataID;  
    }
}

我需要在循环之外使用所有 IDString[] 项目,但不知道该怎么做。 VS C# 是说如果我想使用该变量必须有任何值/声明。谁能帮帮我?

这周我做了几个关于循环的噩梦..

【问题讨论】:

  • 我看不出这段代码有什么问题。我打算回答你应该在循环之前声明变量,但你已经这样做了......
  • VS C# 是说如果我想使用变量必须有任何值/声明,并且声明设置在循环中,我现在不知道如何将其拉出

标签: c# excel loops


【解决方案1】:

你永远不会 instanciate IDString 或给它一个长度。

string[] IDString;

你可能需要这样的东西:

string CellDataID;
//List<T>(s) are more flexible than arrays
//new instantiates it
List<string> IDString = new List<string>;
for (int RowCount = 2; RowCount <= LastRow; RowCount++)
{
    xlRange = (Excel.Range)xlSht.Cells[RowCount, colNumberID];
    CellDataID = (string)xlRange.Text;
    PrinterBox1.Items.Add(CellDataID);
    //this is just wrong.
    //IDString = new string[LastRow];

    //add the string to your list
    IDString.Add(CellDataID);  
}

如果您需要一个数组,只需:

IDString.ToArray()

或者更好的是,只需使用 IEnumerable&lt;T&gt; 将其传递到您的方法中,这将接受 arrayList&lt;T&gt;

【讨论】:

    【解决方案2】:

    试试这个:

    IDString.Any(y => y == something)
    

    你可以在没有 foreach 循环的情况下使用你的数组。

    【讨论】:

      猜你喜欢
      • 2020-04-05
      • 2013-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-17
      • 1970-01-01
      • 2016-05-06
      相关资源
      最近更新 更多