Append Loop Variable to Variable Name

前端 未结 3 1566
夕颜
夕颜 2021-01-26 05:04

I have 5 DataTables that needs to be converted to TXT files. Instead of creating them separately, I thought I use a for loop. Here\'s my code:

Strin         


        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-26 05:46

    You cannot just append a number to a variable name at runtime to magically reference a new variable. What you should do instead is:

    Define an an interface:

    public interface IFileBLO
    {
        DataTable SelectFileForCSV();
    }
    

    Have File1BLO, File2BLO etc all implement IFileBLO and fix the method names so that they are all SelectFileForCSV rather than SelectFile1ForCSV etc.

    Add a lookup for reference these objects:

    var bloList = new IFileBLO[]
    {
        file1BLO, file2BLO, file3BLO, file4BLO, file5BLO
    };
    

    Finally, change your loop to:

    for (int i = 0; i < 5; i++)
    {
        var dtFile = bloList[i].SelectFileForCSV();
        foreach (var dr in dtFile.Rows)
        {
            ...
    

提交回复
热议问题