简体   繁体   中英

Hiding a property (C#)

Well i have the following classes:

  • Player manager (which add players, remove, etc)
  • Player (it does all sort of things)
  • Client (it contains network actions like sending data, recv, etc).

Player manager have an array of Player class and Client class is a composition of Player, with private access because i dont need the user see the Client interface.

It all comes fine, except the problem that i want to use array fixed length instead of a list. Client class is determined at run time and if i want to initialize a player i would need to set it directly on the property or using a setter method, this forces me to make the Client composition as public.

List works perfectly fine on this problem because i can set the Client property on the constructor of Player class, but the idea is to use array fixed length because is faster. Is there any work around to keep Client as private and set it from Player Manager class?

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

Try making it an internal property. The internal keyword makes a type or member invisible outside of the assembly it's defined in.

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.

why not let

FindPlayerSlot(); // return a int type ?

and setting the client property via constructor ?

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

adding the constructor

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.
public Player(Client client)
{
    this.client = client;
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM