Get an instance containing the class

Is it possible to access an object from a member object without transferring and saving the link? In the example below, can a given chair object gain access to a home object without the house passing a link to the member hierarchy?

public class Chair { public string Material { get; set; } public Chair() { Material = "Wood"; } public bool IsInMiami() { // Get instance of House where chair is found House house = ... // Reflection? return house.City.Equals("Miami"); } } public class Room { private List<Chair> _chairs; public Room() { _chairs = new List<Chair>(); _chairs.Add(new Chair()); } } public class House { private List<Room> _rooms; public string City { get; set; } public House() { _rooms = new List<Room>(); _rooms.Add(new Room()); City = "Orlando"; } } 

The answer may be through reflection, but I have no clue how to do this, or there is another way to achieve the same.

Thank you in advance

+4
source share
2 answers

There is no way to do this without the Chair referencing the House. From the Chairperson's point of view, there is no connection between him and the House. In fact, a pulpit could belong to many houses or homes.

+4
source

Firstly, is this an example of some kind of real problem or just an example for learning?

It is definitely not the duty of chari to verify the location of a house. If you want to find all the chairs in Miami, you need to go through the whole tree or give it a link.

+2
source

Source: https://habr.com/ru/post/1434121/


All Articles