如何在 C# 中更新 class 属性 的值?

How to update value of a class property in C#?

如何在每次添加新的 Athlete 对象时增加 属性 TeamSize 的值?因为我无法创建一个变量来存储 TeamSize 的值并在每次新的 Athlete 对象时递增该值,所以我想知道是否有另一种递增 TeamSize 的方法。

public class Team
{
    private Athlete[] athletes;

    public int MaxTeamSize
    {
        get;
        set;
    }

    public string TeamName
    {
        get;
        set;
    }

    public static int TeamSize
    {
        get;
        set;
    }

    public Sport TeamSport
    {
        get;
        set;
    }

    public Team(string name, Sport sport, int maxTeamSize)
    {
        TeamName = name;
        TeamSport = sport;
        MaxTeamSize = maxTeamSize;
        athletes = new Athlete[maxTeamSize];
    }

    public Athlete[] AddAthlete(Athlete a)
    {
        int teamSize = this.athletes.Length;

        if (teamSize < MaxTeamSize)
        {
            athletes[teamSize] = a;
            teamSize++;
            TeamSize = teamSize;
        }

        return this.athletes;
    }

}

你不需要递增。试试这个

 public int TeamSize
    {
        get { return athletes.Count(i => i!=null);}
      
    }
public int MaxTeamSize
    {
        get {retun athletes.Length;}
       
    }
 public Team(string name, Sport sport, int maxTeamSize)
    {
        TeamName = name;
        TeamSport = sport;
        athletes = new Athlete[maxTeamSize];
    }

public Athlete[] AddAthlete(Athlete a)
    {
       

        if (TeamSize < MaxTeamSize)
        {
            athletes[TeamSize] = a;
         }

        return this.athletes;
    }

您需要使用 System.Linq 添加;如果你没有。但也许你最好使用 atlets 列表而不是 atlets 数组。它允许动态添加任意数量的 atlets。

您已将 TeamSize 属性 设置为 static。这是一个关键问题。它对 Team

的每个实例都会产生副作用
    public class Team
    {
        private List<Athlete> athletes;

        public Team(string name, Sport sport, int maxTeamSize)
        {
            TeamName = name;
            TeamSport = sport;
            MaxTeamSize = maxTeamSize;
            athletes = new List<Athlete>(MaxTeamSize);
        }

        public int MaxTeamSize
        {
            get;
            private set;
        }

        public string TeamName
        {
            get;
            set;
        }

        public int TeamSize
        {
            get
            {
                return this.athletes.Count;
            }
        }

        public Sport TeamSport
        {
            get;
            private set;
        }

        public IReadOnlyCollection<Athlete> Athletes
        {
            get
            {
                return athletes;
            }
        }


        public void AddAthlete(Athlete a)
        {

            if (athletes.Count < MaxTeamSize)
            {
                athletes.Add(a);
            }
        }
    }