C# 有没有办法使 class 中对象的属性在 class 本身之外不可编辑?

C# Is there a way to make the properties of an object in a class non-editable outside the class itself?

我正在寻找一种在 class 中放置对象并使其在 class 之外不可编辑(对象本身及其属性)但在外部仍然可见的方法。

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   
    }
}

这样的事情可能吗?我找不到关于这个问题的任何信息,所以如果有人有任何想法,我将不胜感激。

提前致谢!

你可以定义一个只公开你想要的位的接口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
}