开发者

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

开发者 https://www.devze.com 2023-01-05 03:44 出处:网络
Friends, I must create a series of ArrayLists, each containing objects of unknown origin, with each instance assigned to a separate local variable.

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 开发者_如何学JAVAthe criteria outlined above and actually compiles?

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号