隐藏属性(C#)

问题描述:

嗯,我有以下类:隐藏属性(C#)

  • 播放机管理器(其中新增玩家,删除等)
  • 播放器(它的所有排序的东西)
  • 客户端(它包含像发送数据,recv等网络动作)。

播放器管理器有一个播放器类的数组,而客户端类是播放器的组成,有私人访问,因为我不需要用户看到客户端界面。

这一切都很好,除了我想要使用数组固定长度而不是列表的问题。 客户端类是在运行时确定的,如果我想初始化一个玩家,我需要直接在属性上设置它或使用setter方法,这迫使我将客户端组合公开。

List在这个问题上完美无缺,因为我可以在Player类的构造函数上设置Client属性,但是想法是使用数组固定长度,因为速度更快。是否有任何解决方法可以让客户端保持私有状态并将其设置为玩家管理器类?

public class PlayerManager 
{ 
    public Player[] players { get; set; } 

    public PlayerManager(int maxplayers) 
    { 
     players = new Player[maxplayers]; 
    } 

    public void Add(Client client) 
    { 
     Player player = FindPlayerSlot(); 
     player.client = client; //cant do this, client is private property 
    } 

} 

public class Player 
{ 
    private Client client { get; set; } //Need to hide this from user 

    //I can set a constructor here for set the client property, but this would 
    //force me to use a list. 
} 
+0

都在同一个库中的类? –

+0

客户端是网络库的一部分,我有 – ffenix

+0

我建议使用列表比固定数组简单得多。 –

尝试使它成为一个internal财产隐瞒这一点。 internal关键字使其类型或成员在定义的程序集外部不可见。

这是假定这是全部在一个程序集中,用户将引用您的程序集并使用它。如果您有多个程序集需要内部可见,则可以使用[assembly: InternalsVisibleTo("MyOtherAssembly")]来定义唯一可访问标记为内部成员的其他程序集。

另外,List<Client>不会比固定数组慢,除非它调整大小。如果您使用List constructor with an initial capacity,则可以获得与固定阵列相同的性能。

+0

非常完整的答案,内部工作正常,我不知道列表与固定数组相同的性能。 – ffenix

为什么不让

FindPlayerSlot(); // return a int type ? 

,并通过构造函数设置客户端属性?

int playerid = FindPlayerSlot(); 
if (playerid > -1) 
{ 
    Player player = new Player(client); 
} 

添加构造

公共类播放器 { 私人客户端{获得;组; } //需要从用户

//I can set a constructor here for set the client property, but this would 
//force me to use a list. 
public Player(Client client) 
{ 
    this.client = client; 
} 

}