How to get parent property in C # class?

For example, in the following classes, I need to have the Parent property in Cupboard and Shelf . How to do it?

 public class Room { public List<Cupboard> Cupboards { get; set; } } public class Cupboard { public Room Parent { get { } } public List<Shelf> Shelves { get; set; } } public class Shelf { } 
+4
source share
1 answer

You can use the automatically implemented property:

 public class Cupboard { public Room Parent { get; set; } } 

You can also make a private setter and install it in the constructor.

 public class Cupboard { public Cupboard(Room parent) { this.Parent = parent; } public Room Parent { get; private set; } } 

Using:

 Room room = new Room(); Cupboard cupboard = new Cupboard(room); Console.WriteLine(cupboard.Parent.ToString()); 

If you have many objects that have a parent room, you can create an interface so that you can find out which room is the parent of the object without knowing its specific type.

 interface IRoomObject { Room { get; } } public class Cupboard : IRoomObject { // ... } 
+6
source

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


All Articles