子类需要基类中的属性信息
这是显示我试图完成的任务的代码。
public partial class Form1 : Form
{
public List<Player> Players { get; set; }
public Form1()
{
InitializeComponent();
Players = new List<Player>();
Players.Add(new Player() { ID = "Hero", Stack = 1000 });
Players.Add(new Player() { ID = "Villain", Stack = 500 });
MessageBox.Show(Players[0].Chipleader.ToString());
}
}
public class Player
{
public string ID { get; set; }
public int Stack { get; set; }
public bool Chipleader
{
get
{
// Dependent on the stacks of the other players
return Stack == Players.Max(S => S.Stack);
}
}
}
我希望每个 Player 对象都有一个属性“Chipleader”,如果该玩家拥有最大的筹码量,则指示 true。玩家对象需要其他玩家的属性(基类中的玩家列表)才能执行此操作。我需要此属性位于 Player 类中的原因是因为我正在使用 ObjectListView在列表视图中列出我的播放器对象。我希望有人能向我展示一种简单/合乎逻辑的方法来做到这一点。
Here is the code that shows what I try to accomplish.
public partial class Form1 : Form
{
public List<Player> Players { get; set; }
public Form1()
{
InitializeComponent();
Players = new List<Player>();
Players.Add(new Player() { ID = "Hero", Stack = 1000 });
Players.Add(new Player() { ID = "Villain", Stack = 500 });
MessageBox.Show(Players[0].Chipleader.ToString());
}
}
public class Player
{
public string ID { get; set; }
public int Stack { get; set; }
public bool Chipleader
{
get
{
// Dependent on the stacks of the other players
return Stack == Players.Max(S => S.Stack);
}
}
}
I want every Player object to have a property "Chipleader" indicating true if the that player has the biggest stack. The player object needs properties of the other players (list of players in base class) to be able to do this. The reason I need this property to be in the Player class is because I'm using ObjectListView to list my player objects in a listview. I hope someone can show me a simple/logical way to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

通常,您的“游戏”将管理领先的玩家,而不是其他玩家。如果一个类需要了解其他类才能正常运行,这通常是一个糟糕的设计。
相反,我建议让您的“游戏”(表单)包含一个 Chipleader 属性,该属性返回领先的玩家,即:
如果您确实需要在 Player 上使用此方法,请创建一个方法,如下所示:(
我还建议将游戏逻辑移动到它自己的“游戏”类中,并将其封装在表单中,而不是将游戏逻辑放在 Form1 中)
Typically, your "game" would manage which player is in the lead, not the other players. It's typically a bad design to have a class require knowledge of other classes in order to function correctly.
I would, instead, suggest having your "game" (the form) contain a Chipleader property that returned the player in the lead, ie:
If you truly need this on Player, make a method, like so:
(I'd also recommend moving the Game logic into it's own "Game" class, and encapsulate that in the form, instead of having the game logic in Form1)