访问对象图中的根类封装属性
本文关键字:封装 属性 对象图 访问 | 更新日期: 2023-09-27 18:27:24
我目前正在编写一个冒险游戏创建者框架,到目前为止我有以下课程:
// Base class that represents a single episode from a complete game.
public abstract class Episode : IEpisode
{
public RoomList Rooms {get; }
public ArtefactList Artefacts {get; }
public Episode()
{
Rooms = new RoomList();
Artefacts = new ArtefactList();
}
}
// This is a list of all objects in the episode.
public ArtefactList : List<IArtefact>
{
public IArtefact Create( UInt32 id, String text )
{
IArtefact art = new Artefact( id, text );
base.Add( art );
return art;
}
}
// This is a list of all rooms in the episode.
public RoomList : List<IRoom>
{
public IRoom Create( UInt32 id, String text )
{
IRoom rm = new Room( id, text );
base.Add( rm );
return rm;
}
}
public class Room : IRoom
{
public UInt32 Id { get; set; }
public String Text { get; set; }
public IList<IArtefact> Artefacts
{
get
{
return ???what??? // How do I access the Artefacts property from
// the base class:
// (Room --> RoomList --> Episode)
}
}
}
public class Artefact : IArtefact
{
public UInt32 Id { get; set; }
public String Text { get; set; }
public IRoom CurrentRoom { get; set; }
}
public interface IArtefact
{
UInt32 Id { get; set; }
String Text { get; set; }
IRoom CurrentRoom { get; set; }
}
public interface IRoom
{
UInt32 Id { get; set; }
String Text { get; set; }
IList<IArtefact> Artefacts {get; }
}
我想知道的是,Room
类应该如何访问Episode
类的封装的Artefacts
属性,而不必一直向下传递对Episode
的引用,即Episode
->RoomsList
->Room
。
房间和工艺品之间存在一对多的关系。因此,您必须在RoomList中初始化此关系。创建方法:
public IRoom Create( UInt32 id, String text , ArtefactList artefacts)
{
IRoom rm = new Room( id, text , artefacts);
base.Add( rm );
return rm;
}
创建房间时,您可以这样做:
var episode = new Episode();
episode.Rooms.Create(1, "RoomText", episode.Artefacts);
您应该对ArtefactList执行同样的操作。创建为Artefact需要IRoom实例。