How can I create a sequence of numbered variables at run time?

牧云@^-^@ 提交于 2019-11-29 18:28:14

You cannot change the name of a variable during execution, since the code (even c# code) was compiled with a certain variable name. If you could change the name during execution then it would cause problems.

For example, if the language allowed to change variable names then when you try to access a variable named 'var1' the compiler has no idea if during execution that variable name changed and now is called 'x'.

Something you could try to do is to allow your program to dynamically compile some code but this is probably not the right solution to your problem. If you explain better what you need then we could provide you with an effective solution.

Hope this helped

EDIT: Seeing your editions I can tell you that it is impossible with the approach you are currently using. I could suggest you the following:

int i = 0;
List<ArrayList> masterList = new List<ArrayList>();
foreach (something)
{
     masterList.Add(new ArrayList());
     i++;
}

If what you need is to have each ArrayList to have a specific name you can recall you can use a dictionary:

int i = 0;
Dictionary<string, ArrayList> masterList = new Dictionary<string, ArrayList>();
foreach (something)
{
     masterList.Add("oArr" + i.ToString(), new ArrayList());
     i++;
}
ArrayList al = masterList["oArr1"];

Would this work for you?

var arrayLists = new List<ArrayList>();
var i = 0;
foreach(var item in list)
{
    arrayLists.Add(new ArrayList());
    i++;
}

Then you can access each array list by index.

Use a List of ArrayLists.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!