C#:创建子对象的父列表 class

C#: creating a parent list class of children objects

我从 C# 代码开始...

我想创建一个名为“VolumeList”的class,它是“Volume”对象的列表。

所以像这样:

public class Volume
{
    private string name;

    public Volume(string name)
    {
        this.name = name;
    }

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public static List<Volume> VolumeList { get; set; } = new List<Volume>();
}

但是当我这样做时,我无法直接访问 VolumeList。我必须用 Volume.VolumeList 来调用它...(这不合逻辑...)我想要这样的东西:

VolumeList.Current.Name (it should return the name of the current volume)

VolumeList.Last.Name (it should return the name of the last volume of the list)

VolumeList.Add = ... (it adds a new volume to the VolumeList)

所以我也想要IEnumerable属性(我认为是这个名字..)。

请你帮我创建正确的 class 层次结构,并告诉我如何访问存储在 VolumeList 中的具有列出的(“Current”,Last,...)属性的我的 Volume 对象?

例如,如果我在组合框中加载我的 VolumeList,并且我 select 一个卷,这个卷在我的应用程序中一直得到“当前”属性。

提前致谢。

在基本 OOP 中,class 的实例无法访问静态方法或属性。它们是在编译时创建的。我们必须像使用 class 名称访问常量变量一样访问它们,就像命名空间错觉一样。您需要做的是删除静态声明并执行此操作。您也不需要 this 关键字。 C# 很聪明,知道您要访问什么

public class Volume {
    private string _name;

    public Volume(string name) {
        _name = name;
    }
    
    public string Name {
        get { return _name; }
        set { _name = value; }
    }
   
    public List<Volume> VolumeList = new List<Volume>();

}

然后您可以使用 LINQ 来操作卷列表中的项目。使用 LINQ TUTORIAL 了解 LINQ 的工作原理。

用法

Volume vol = new Volume("First Volume Object");
vol.VolumeList.Add(new Volume("First Sub Volume"));
vol.VolumeList.Add(new Volume("Second Sub Volume"));
        
Console.WriteLine(vol.VolumeList.First().Name);
Console.WriteLine(vol.VolumeList.Last().Name);