Наследование: как я могу использовать переменные из дочернего класса? - PullRequest
0 голосов
/ 29 октября 2018

Как я могу использовать переменные из дочернего класса в Program.cs? Я могу использовать только те, которые объявлены в классе Player. Однако я смог «объединить» параметры дочернего класса с родительскими переменными Screenshot of container

Но когда я пытаюсь использовать эти переменные, они отсутствуют: Screenshot of variables missing

Как вызвать переменные из дочернего класса? Если это возможно.

abstract class Player
{
    public string Team { get; set; }
    public string Name { get; set; }
    public string surName { get; set; }
    public DateTime birthDate { get; set; }
    public int gamesCount { get; set; }
    public Player()
    { }
    public Player(string Team, string Name, string surName, DateTime birthDate, int gamesCount)
    {
        this.Team = Team;
        this.Name = Name;
        this.surName = surName;
        this.birthDate = birthDate;
        this.gamesCount = gamesCount;
    }

}


class BasketballPlayers : Player
{
    public int Rebounds { get; set; }
    public int Assists { get; set; }
    public int scorePoints { get; set; }
    public BasketballPlayers()
    { }
    public BasketballPlayers(string Team, int gamesCount, string Name, string surName, DateTime birthDate, int scorePoints, int Rebounds, int Assists)
        : base(Team, Name, surName, birthDate, gamesCount)
    {
        this.scorePoints = scorePoints;
        this.Rebounds = Rebounds;
        this.Assists = Assists;
    }
class FootballPlayers : Player
{
    public int yellowCards { get; set; }
    public int scorePoints { get; set; }
    public FootballPlayers()
    { }
    public FootballPlayers(string Team, int gamesCount, string Name, string surName, DateTime birthDate, int scorePoints, int yellowCards)
        : base(Team, Name, surName, birthDate, gamesCount)
    {
        this.yellowCards = yellowCards;
        this.scorePoints = scorePoints;
    }

ОБНОВЛЕНИЕ: PlayersContainer bPlayers = new PlayersContainer(100) для баскетболистов PlayersContainer fPlayers = new PlayersContainer(100); это для футболистов.

    static void ReadDataFromFiles(string basketBallFile, string footBallFile, string teamInfoFile, PlayersContainer bPlayers, PlayersContainer fPlayers)
    {
        ReadPlayerData(basketBallFile, bPlayers);
        ReadPlayerData(footBallFile, fPlayers);
    }
    static void ReadPlayerData(string filePath, PlayersContainer Players)
    {
        using (StreamReader reader = new StreamReader(filePath))
        {
            string line = null;
            string playerType = null;
            line = reader.ReadLine();
            if (line != null)
            {
                playerType = line;
            }
            int i = 0;
            while (null != (line = reader.ReadLine()))
            {
                string[] values = line.Split(';');
                string Team = values[0];
                string surName = values[1];
                string Name = values[2];
                DateTime birthDate = DateTime.Parse(values[3]);
                int gamesCount = int.Parse(values[4]);
                int scorePoints = int.Parse(values[5]);

                switch (filePath)
                {
                    case "../../Krepsininkai.csv":
                        int Rebounds = int.Parse(values[6]);
                        int Assists = int.Parse(values[7]);
                        BasketballPlayers bPlayer = new BasketballPlayers(Team, gamesCount, Name, surName, birthDate, scorePoints, Rebounds, Assists);
                        Players.AddPlayer(bPlayer);
                        break;
                    case "../../Futbolininkai.csv":
                        int yellowCards = int.Parse(values[6]);
                        FootballPlayers fPlayer = new FootballPlayers(Team, gamesCount, Name, surName, birthDate, scorePoints, yellowCards);
                        Players.AddPlayer(fPlayer);
                        break;

                }
            }
        }

    }

когда я отлаживаю, я вижу, что эти эксклюзивные параметры добавлены, я имею в виду Rebounds, Assists, scorePoints для игроков в баскетбол и yellowCards, scorePoints для футболистов. Но потом я пытаюсь получить к ним доступ, мне нужны методы для этого или что? Я могу вызывать только параметры базового класса.

1 Ответ

0 голосов
/ 29 октября 2018

Лучше всего спроектировать эту потребность, создав абстрактный базовый класс со свойствами, которые вы хотите вызвать. Просто сделайте, чтобы производный или дочерний класс переопределяли свойство (и). Затем, когда кто-то имеет ссылку или через интерфейс, связанный с базой, если его экземпляр действительно является дочерним, то свойство Child вызывается / используется.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...