gpt4 book ai didi

C# 从父类继承属性

转载 作者:行者123 更新时间:2023-11-30 19:46:24 25 4
gpt4 key购买 nike

我希望我的玩家对象继承锦标赛中的筹码总和。我得到(试图除以零。)我认为这是因为它无法从父 Tournament 对象继承 Chips。为什么这不起作用?

public partial class Form1 : Form
{
public Tournament Tournament { get; set; }

public Form1()
{
InitializeComponent();

Tournament = new Tournament();
Tournament.PlayerList.Add(new Player("Hero", 5000));
Tournament.PlayerList.Add(new Player("Villain1", 3000));
Tournament.PlayerList.Add(new Player("Villain2", 4000));

MessageBox.Show(Tournament.PlayerList[0].StackPercentage.ToString());
}
}

public class Tournament
{
public List<Player> PlayerList { get; set; }
public int Chips
{
get
{
return PlayerList.Sum(S => S.Stack);
}
}

public Tournament()
{
PlayerList = new List<Player>();
}
}

public class Player : Tournament
{
public string ID { get; set; }
public int Stack { get; set; }
public double StackPercentage
{
get
{
return Stack / Chips;
}
}

public Player(string _ID, int _Stack)
{
ID = _ID;
Stack = _Stack;
}
}

最佳答案

您不应该从 Tournament 派生 Player。通过这样做,您是在说每个玩家都是一场锦标赛。

尝试这样的事情:

public interface IPlayer {}

public abstract class Player : IPlayer
{
public ITournament CurrentTournament { get; set; }
}

public class PokerPlayer : Player
{
public PokerPlayer() {}
public int CurrentChips { get; set; }

public double StackPercentage
{
get { return this.CurrentChips / (PokerTournament)this.CurrentTournament.StartingChips; }
}
}

public interface ITournament {}

public abstract class Tournament : ITournament
{
public List<Player> Players { get; set; }
public int PlayerCount { get { return this.Players.Count; } }
}

public class PokerTournament : Tournament
{
private PokerTournament() {}
public PokerTournament(int startingChips)
{
if(startingChips < 1) throw new ArgumentException("Invalid starting amount.", "startingChips");
this.StartingChips = startingChips;
}

public int StartingChips { get; set; }
}

关于C# 从父类继承属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8636568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com