简体   繁体   English

c#如何创建动态列表/数组

[英]c# How to create a dynamic list/array

Actually, I have this : 实际上,我有这个:

public ArrayList _albumId;
public ArrayList _albumName;
public ArrayList _nbPhotos;

And when I have a new album, I add a line on each ArrayList. 当我有一张新专辑时,我在每个ArrayList上添加一行。 Do you know something to do it with only one list or array ? 你知道只用一个列表或数组做些什么吗? Thanks 谢谢

First of all, don't use ArrayList - use generic List<T> . 首先,不要使用ArrayList - 使用通用List<T>

Second - instead of having separate list for each attribute of album, create Album class with all required attributes, and keep albums in List<Album> : 其次 - 创建具有所有必需属性的Album类,而不是为专辑的每个属性设置单独的列表,并将专辑保留在List<Album>

public class Album
{
   public int Id { get; set; }
   public string Name {get; set; }
   public int CountOfPhotos {get; set; }
}

Adding new album: 添加新相册:

_albums.Add(new Album { Id = 2, Name = "Foo", CountOfPhotos = 42 });

Where albums list declared as 将专辑列表声明为

List<Album> _albums = new List<Album>();

Why keep information about the same thing broken apart into multiple arrays? 为什么要将有关同一事物的信息分成多个数组?

Create an Album object. 创建一个Album对象。 Something like: 就像是:

public class Album
{
    public int ID { get; set; }
    public string Name { get; set; }
    // other properties, etc.
}

And have a list of albums : 并有一个专辑列表:

var albums = new List<Album>();

When adding a new album, add a new album: 添加新相册时,添加新相册:

var newAlbum = new Album
{
    ID = someValue,
    Name = anotherValue
}
albums.Add(newAlbum);

Keep information about an object encapsulated within that object, not strewn about in other disconnected variables. 保留有关封装在该对象中的对象的信息,而不是散布在其他断开连接的变量中。


As an analogy, consider the act of parking a car in a parking lot. 作为类比,考虑在停车场停车的行为。 With a collection of objects, the parking lot has a collection of spaces and each car goes into a space. 通过一系列物品,停车场拥有一系列空间,每辆车都进入一个空间。 Conversely, with separate arrays of values, the process for parking a car is: 相反,使用单独的值数组,停放汽车的过程是:

  1. Take the car apart. 把车拆开。
  2. Put the tires in the tire space, the windows in the window space, the doors in the door space, etc. 将轮胎放在轮胎空间,窗户空间的窗户,门空间的门等。
  3. When you want to get the car back, go around to all the spaces and find your parts. 如果您想要将车开回去,请到处寻找所有空间并找到您的零件。 (Hope that you found the right ones.) (希望你找到合适的人。)
  4. Re-build the car. 重新建造汽车。

Modeling encapsulated objects just makes more sense. 对封装对象进行建模更有意义。

Use a generic list. 使用通用列表。

Define a class, for smaple: 为smaple定义一个类:

public class Album
{
   public int Id { get; set; }
   public string Name { get; set; }
   public string[] AlbumPhotos { get; set; }
}

And use it in a generic list: 并在通用列表中使用它:

var albums = new List<Album>();

albums.Add(new Album() { Id = 1, Name = "Ramones" };
albums.Add(new Album() { Id = 2, Name = "Leave Home" };
albums.Add(new Album() { Id = 3, Name = "Rocket To Russia" };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM