properties - How to have a parent property in C# class? -
for example, in following classes need have parent property in cupboard , shelf. how do it?
public class room { public list<cupboard> cupboards { get; set; } } public class cupboard { public room parent { { } } public list<shelf> shelves { get; set; } } public class shelf { }
you can use automatically implemented property:
public class cupboard { public room parent { get; set; } } you can choose make setter private , set in constructor.
public class cupboard { public cupboard(room parent) { this.parent = parent; } public room parent { get; private set; } } usage:
room room = new room(); cupboard cupboard = new cupboard(room); console.writeline(cupboard.parent.tostring()); if have many objects have parent room might want create interface can find out room object's parent without having know specific type.
interface iroomobject { room { get; } } public class cupboard : iroomobject { // ... }
Comments
Post a Comment