如何在 C# 类中拥有父属性?

发布于 2024-10-14 10:27:34 字数 374 浏览 2 评论 0原文

例如,在以下类中,我需要在 CupboardShelf 中有一个 Parent 属性。我该怎么做?

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
{

}

For example, in the following classes I need to have a Parent property in Cupboard and Shelf. How do I 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
{

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只为守护你 2024-10-21 10:27:34

您可以使用自动实现的属性:

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

您还可以选择将 setter 设为私有并在构造函数中设置它。

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

    public Room Parent { get; private set; }
}

用法:

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

如果您有许多对象都有一个父房间,您可能需要创建一个接口,以便您可以找出哪个房间是对象的父房间,而不必知道其具体类型。

interface IRoomObject
{
    Room { get; }
}

public class Cupboard : IRoomObject
{
    // ...
}

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
{
    // ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文