开发者

How to have a parent property in C# class?

开发者 https://www.devze.com 2023-02-06 13:43 出处:网络
For example, in the following classes I need to have a Parent property in Cupboard and Shelf. How do I do it?

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
{
    // ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号