获取对象创建的当前对象

本文关键字:对象 取对象 创建 获取 | 更新日期: 2023-09-27 18:37:17

让我们假设

public abstract class Game
{
    // Base
}
public class Poker : Game
{
    // Lobby Object
    // NUMBER OF PLAYERS ( Max )   ----------
}                                            '
                                             '
public class Lobby                           '
{                                            '
    // List<Tables>                          '
}                                            '
                                             '
public class Table                           '
{                                            '
    // List<Player>                <---------'
}

如何在没有冗余传递的情况下从对象访问玩家数量


编辑一
你误解了我的问题,对不起。
我想从游戏类型访问可以加入此表的最大数量。
所以如果这是一个扑克桌,我想得到等于 10 的玩家人数


编辑二
不同的游戏类型:红心,黑桃,扑克,估计,...等
最大玩家人数分别为:4,4,10,4等。


编辑三
再次,误解了我的问题,我希望能够执行以下操作:

当玩家尝试加入一个表时,我比较目标表当前 玩家数量与其游戏类型最大玩家数量,所以我决定 如果玩家可以或不能加入它!

获取对象创建的当前对象

我认为需要对以下关系进行建模:

public abstract class Game
{
    // force all Game descendants to implement the property
    public abstract int MaxPlayers { get; } 
}
public class Poker : Game
{
    // Lobby Object
    public List<Lobby> Lobbies { get; set; }
    // NUMBER OF PLAYERS ( Max )
    // the abstract prop needs to be overridden here
    public override int MaxPlayers 
    { 
       get { return 4; } 
    }
}   
public class Lobby
{
    public List<Table> Tables { get; set; }
}
public class Table                           
{                    
    public Game CurrentGame { get; set; }
    public List<Player> Players { get; set; }
    // force the Game instance to be provided as ctor param.
    public Table(Game gameToStart)
    {
        CurrentGame = gameToStart;
    }
}
注入实例化

Table时正在播放的Game

var pokerGame = new Poker();
// more code here, etc etc
var myTable = new Table(pokerGame);

要获取Table实例中允许的最大玩家数,请执行以下操作:

var maxAllowed = Table.CurrentGame.MaxPlayers;

使用 LINQ 到对象,您可以非常轻松地做到这一点。

public abstract class Game
{
}
public class Poker : Game
{
    private Lobby lobby = new Lobby();
    public int MaxPlayers         
    { 
        get
        {           
           int count = lobby.tableList.Sum(t => t.playerList.Sum(c => t.playerList.Count));
           return count;
        }                 
    }

public class Lobby
{
    public List<Table> tableList { get; set; }
}
public class Table
{
    public List<Player> playerList { get; set; }
}
public class Player
{
}