Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从另一个列表中访问类中的列表_C# - Fatal编程技术网

C# 如何从另一个列表中访问类中的列表

C# 如何从另一个列表中访问类中的列表,c#,C#,我正在做一个将动物分类成马车的应用程序。 动物存储在动物列表中(位于货车类) 货车存储在货车列表中(位于列车类别中) 我想从火车班上看到每辆货车上的动物 我有一辆旅行车: class Wagon { List<Animal> animals = new List<Animal>(); public Wagon(Animal animal) { animals.Add(animal);

我正在做一个将动物分类成马车的应用程序。 动物存储在动物列表中(位于货车类) 货车存储在货车列表中(位于列车类别中) 我想从火车班上看到每辆货车上的动物

我有一辆旅行车:

class Wagon
    {
        List<Animal> animals = new List<Animal>();

        public Wagon(Animal animal)
        {
            animals.Add(animal);
        }
    }
货车
{
列出动物=新列表();
公共马车(动物)
{
动物。添加(动物);
}
}
还有一班火车:

class Train
    {
        List<Wagon> wagons = new List<Wagon>();

public void AddLargeHerbivore(Animal animal)
        {
            foreach(Wagon w in wagons)
            {
                //foreach(Animal a in w.animals) {} does not work :(
                //do stuff
            }
        }
    }
班列
{
列表货车=新列表();
大型食草动物(动物)
{
foreach(货车中的货车w)
{
//foreach(动物a在w.animals中){}不起作用:(
//做事
}
}
}

我正在尝试访问每辆货车的动物列表,在货车列表中。但是,我看不到任何处理动物的方法。我如何做到这一点?

您必须将货车类中的动物列表公开

class Wagon
{
    public List<Animal> animals = new List<Animal>();

    public Wagon(Animal animal)
    {
        animals.Add(animal);
    }
}
货车
{
公开名单

但不应公开字段,而应将其转换为属性:

private List<Animal> _animals;

public List<Animal> Animals
{
    get { return _animals; }
    set { _animals = value; } //You can do additional checks in the setter
}
private List\u动物;
公众动物名录
{
获取{return}
set{{u animals=value;}//您可以在setter中执行其他检查
}

为什么
旅行车的构造器将单个动物添加到该列表中?您应该提供一个接受
IEnumerable
的构造器,或者提供一个方法
AddAnimal
,该方法接受单个动物。这里的另一个问题是对OOP原则的误解。旅行车有一个动物列表,但在创建wago时n、 您只允许添加一个动物。为每个动物创建一个新的货车不会导致一个货车上有许多动物,而是会导致许多货车,每个货车上有一个动物,这可能不是您要寻找的。(请注意,Train类在这方面是正确的:它通过一个可以多次调用的方法添加动物。但是构造函数(如在Cargo中)每个对象只能调用一次。请尽量避免列表/集合属性的setter。如果需要更改数据,可以使用Add和Clear方法。请尽量避免使用公共字段。在我看来,如果以这种方式公开数据,将更难跟踪使用情况。@默认值谢谢您的评论,您完全正确。我只是poi他一直在向他解释为什么他的代码不起作用,但更好的做法是通过操作列表的方法提供必要的功能。