C# - why am I getting an empty collection?

后端 未结 1 1026
被撕碎了的回忆
被撕碎了的回忆 2021-01-17 04:03

How come people collection has items in it only if I override it within the subclasses? Here\'s the code. If I uncomment the overridden methods, then my collection has 2 peo

相关标签:
1条回答
  • 2021-01-17 04:30
    Thing park = new Park();
    

    Here you are instantiating a Park object and assigning it to a variable whose type is Thing. So far, so good.

    park = new PersonA(park);
    

    Here you are instantiating a PersonA, and because you pass your Park object to the constructor, the constructor adds itself to the Park's People collection. So that collection now contains one person. Again, so far, so good.

    However, you then assign the new PersonA object to the park variable. This is not a runtime error because the variable has type Thing and a PersonA is a Thing, but it's almost certainly a logic error on your part, because I can't conceive of a reason why you'd want a variable called park that refers to a person.

    The critical thing is that at this point, park.People doesn't refer to the Park object's collection of people; it refers to the PersonA object's collection of people, which is empty.

    park = new PersonB(park);
    

    Now when you invoke the PersonB constructor, you're not passing it a Park object; you're passing it the PersonA object that you assigned to the park variable. So the PersonB constructor adds itself to the PersonA's People collection, which now contains one person.

    But again, you're assigning the result to park. So now park contains a PersonB object whose People collection is empty. Which is why this:

    Console.WriteLine(park.people.Count);
    

    Prints zero.

    0 讨论(0)
提交回复
热议问题