c#有没有办法在类本身之外不可用的类中对象的属性?

发布于 2025-01-21 11:38:10 字数 678 浏览 0 评论 0原文

我正在寻找一种在类中拥有一个对象,并使该对象在班级本身之外的不可分割的(对象本身及其属性),但外部仍然可见。

internal class Room
{
    public string Description { get; set; }
}

internal class RoomController
{
    public Room Room { get; private set; }
    
    public RoomController()
    {
        Room = new Room();
    }

    //Edit the room inside this class
}

internal class Foo
{
    public void SomeMethod()
    {
        RoomController rc = new RoomController();
        
        rc.Room.Description = "something";   // This should not be allowed 
        string roomDesc = rc.Room.Description;   // This should be fine   
    }
}

有可能吗?关于这个问题,我找不到任何东西,所以如果有人有任何想法,我会很感激。

提前致谢!

I am looking for a way to have an object in a class and make it non-editable (the object itself AND its properties) outside the class itself but still visible outside.

internal class Room
{
    public string Description { get; set; }
}

internal class RoomController
{
    public Room Room { get; private set; }
    
    public RoomController()
    {
        Room = new Room();
    }

    //Edit the room inside this class
}

internal class Foo
{
    public void SomeMethod()
    {
        RoomController rc = new RoomController();
        
        rc.Room.Description = "something";   // This should not be allowed 
        string roomDesc = rc.Room.Description;   // This should be fine   
    }
}

Is something like that possible? I couldn't find anything regarding the issue so I would be grateful if anyone has any ideas.

Thanks in advance!

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

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

发布评论

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

评论(1

我的鱼塘能养鲲 2025-01-28 11:38:10

您可以定义一个仅揭示您想要公开的位的接口:

internal interface IReadonlyRoom
{
  string Description { get; }  //note only getter exposed
}

internal class Room : IReadonlyRoom
{
    public string Description { get; set; }
}

internal class RoomController
{
    private Room _room;

    public IReadonlyRoom Room => _room;

    public RoomController()
    {
        _room = new Room();
    }

    //edit using _room
}

You could define an interface that only exposes the bits you want public:

internal interface IReadonlyRoom
{
  string Description { get; }  //note only getter exposed
}

internal class Room : IReadonlyRoom
{
    public string Description { get; set; }
}

internal class RoomController
{
    private Room _room;

    public IReadonlyRoom Room => _room;

    public RoomController()
    {
        _room = new Room();
    }

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