0

好吧,我有以下课程:

  • 玩家管理器(添加、移除等)
  • 播放器(它可以做各种事情)
  • 客户端(它包含发送数据、recv 等网络操作)。

播放器管理器有一个播放器类数组,客户端类是播放器的组合,具有私有访问权限,因为我不需要用户查看客户端界面。

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

List 在这个问题上工作得很好,因为我可以在 Player 类的构造函数上设置 Client 属性,但想法是使用数组固定长度,因为它更快。是否有任何解决方法可以将 Client 保持为私有并从 Player Manager 类中设置它?

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

2 回答 2

1

试着把它变成一个internal属性。关键字使类型或成员在internal定义它的程序集之外不可见。

That's assuming this is all in a single assembly and the user will be referencing your assembly and using it. If you have more than one assembly you need the internals visible to, you can use [assembly: InternalsVisibleTo("MyOtherAssembly")] to define the only other assemblies that have access to the members marked as internal.

Additionally, a List<Client> isn't going to be any slower than a fixed array except for when it's resizing. If you use the List constructor with an initial capacity, you can get the same performance as a fixed array.

于 2013-01-19T08:38:42.560 回答
0

为什么不让

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

}

于 2013-01-19T08:38:27.023 回答