在for循环外部使用变量

时间:2018-04-18 10:59:17

标签: c# excel loops

我遇到了问题:

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#说如果我想使用它,变量必须有任何值/声明。任何人都可以帮助我吗?

本周我有几个关于循环的噩梦......

2 个答案:

答案 0 :(得分: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<T>将其传递到您的方法中,然后接受arrayList<T>

答案 1 :(得分:0)

试试这个:

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

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

相关问题