How to create dynamic incrementing variable using “for” loop in C#

后端 未结 6 649
南方客
南方客 2021-01-07 03:42

How to create dynamic incrementing variable using \"for\" loop in C#? like this: track_1, track_2, track_3, track_4. so on.

6条回答
  •  旧巷少年郎
    2021-01-07 03:53

    No, we can't create dynamically named variables in a loop. But, there are other elegant ways to address the problem instead of creating dynamically named variables.

    One could be, create an array or list before the loop and store values in array / list items in the loop. You can access the array / list later anywhere in your code. If you know which variable you want to use (track_1, track_2, ...), you can simply access it from the array / list (tracks[1], tracks[2], ...).

    List tracks = new List();
    for (int i = 1; i < limit; i++)
    {
        Track track = new Track();
        tracks.Add(track);
        ...
    }
    

提交回复
热议问题