How can I create a sequence of numbered variables

2019-01-29 14:28发布

Friends, I must create a series of ArrayLists, each containing objects of unknown origin, with each instance assigned to a separate local variable.

So far, so good... But I also need each local variable's name to follow a very specific pattern: the name should begin with "oArr", followed by one or more digits reflecting that particular array's position within the sequence. Furthermore, I will not know at compile-time how many of these arrays - and hence, how many local variables - I will be needing!

It strikes me that this is perhaps a problem that could be solved by the availability of dynamic types in C# 4.0, however I am not at all familiar with their use. How might I take code like this...

int i=0;
foreach(something)
{
    ArrayList oArr+i=new ArrayList();
    i++;
}

...and turn it into something that matches the criteria outlined above and actually compiles?

Alternately, is there a more simple, sane approach to this problem?

3条回答
倾城 Initia
2楼-- · 2019-01-29 14:51

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.

查看更多
欢心
3楼-- · 2019-01-29 14:52

Use a List of ArrayLists.

查看更多
祖国的老花朵
4楼-- · 2019-01-29 14:58

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"];
查看更多
登录 后发表回答