How to have a parent property in C# class?
For example, in the following classes I need to have a Parent property in Cupboard and Shelf. How do I do it?
publi开发者_高级运维c class Room
{
    public List<Cupboard> Cupboards { get; set; }
}
public class Cupboard
{
    public Room Parent 
    {
        get
        {
        }
    }
    public List<Shelf> Shelves { get; set; }
}
public class Shelf
{
}
You can use an automatically implemented property:
public class Cupboard
{
    public Room Parent { get; set; }
}
You can also choose to make the setter private and set it in the 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 you have many objects that all have a parent room you might want to create an interface so that you can find out which room is an object's parent without having to know its specific type.
interface IRoomObject
{
    Room { get; }
}
public class Cupboard : IRoomObject
{
    // ...
}
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论