Проблемы с наследованием в классах C#

229
11 мая 2018, 09:31

Имеется сейчас два класса- один базовый, другой наследуется от первого. Код первого класса:

using ClassLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleProject
{
    class Program
    {
        public static Person[] person;
        public static int n=0;
        static void Main(string[] args)
        {
            System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)
            System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
            customCulture.NumberFormat.NumberDecimalSeparator = ".";
            System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
            Console.OutputEncoding = Encoding.Unicode;
            Console.InputEncoding = Encoding.Unicode;
            Console.Title = "Лабораторна робота №7";
            Console.SetWindowSize(100, 25);
            Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.DarkBlue; Console.Clear();

            int x=1;
            while (x != 0)
            {
                Console.WriteLine("\t1. Додати людину\n\t" +
                    "2. Додати студента\n\t" +
                    "3. Додати абітурієнта\n\t" +
                    "4. Додати викладача\n\t" +
                    "5. Додати користувача бібліотеки\n\t" +
                    "6. Роздрукувати інформацію про людей\n\t" +
                    "0. Вихід" +
                    "\n-->");
                while (!int.TryParse(Console.ReadLine(), out x))
                {
                    Console.WriteLine("Помилка введення значення. Будь-ласка повторіть введення значення ще раз!");
                }

                switch (x)
                {
                    case 1: { CreatePerson(); break; }
                    case 2: { CreateStudent(); break; }
                    case 3: { CreateEnterant(); break; }
                    case 4: {  break; }
                    case 5: {  break; }
                    case 6: { PersonShow();  break; }
                    case 7: {  break; }
                }
            }

            Console.Read();
        }
        private static void CreateEnterant()
        {
            throw new NotImplementedException();
        }
        private static void CreateStudent()
        {
           person[n] = new Student();

            Console.WriteLine("Введіть ім'я:");
            person[n].FirstName = Console.ReadLine();
            Console.WriteLine("Введіть прізвище:");
            person[n].LastName = Console.ReadLine();
            Console.WriteLine("Введіть дату народження:");
            person[n].DateOfBirth = Console.ReadLine();
            Console.WriteLine("Введіть курс:");
            person[n].Course = Console.ReadLine();
            Console.WriteLine("Введіть групу:");
            person[n].Group = Console.ReadLine();
            Console.WriteLine("Введіть факультет:");
            person[n].Faculty = Console.ReadLine();
            Console.WriteLine("Введіть навчальний заклад:");
            person[n].Vnz = Console.ReadLine();
            n++;
        }
        private static void PersonShow()
        {
            for(int i=0; i<person.Length;i++)
            {
                person[i].ShowInfo();
            }
        }
        public static void CreatePerson()
        {

                person[n] = new Person();
                Console.WriteLine("Введіть ім'я:");
                person[n].FirstName = Console.ReadLine();
                Console.WriteLine("Введіть прізвище:");
                person[n].LastName = Console.ReadLine();
                Console.WriteLine("Введіть дату народження:");
                person[n].DateOfBirth = Console.ReadLine();
            n++;
        }
    }
}

Код второго класса:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary
{
   public class Student : Person
    {
        protected string Course { get; set; }
        public string Group { get; set; }
        public string Faculty { get; set; }
        public string Vnz { get; set; }
        public void SetCourse(string course)
        {
            Course = course;
        }
        public string GetCourse()
        {
            return Course;
        }
        public void SetGroup(string group)
        {
            Group = group;
        }
        public string GetGroup()
        {
            return Group;
        }
        public void SetFaculty(string facul)
        {
            Faculty = facul;
        }
        public string GetFaculty()
        {
            return Faculty;
        }
        public void SetVnz(string vnz)
        {
            Vnz = vnz;
        }
        public string GetVnz()
        {
            return Vnz;
        }

        public Student( Student pers)
        {
            this.FirstName = pers.FirstName;
            this.LastName = pers.LastName;
            this.DateOfBirth = pers.DateOfBirth;

        }
        public Student(string firstName, string lastName, string dateOfBirth, string cors, string gro, string facul, string vnz)
            : base(firstName, lastName, dateOfBirth)
        {
            Course = cors;
            Group = gro;
            Faculty = facul;
            Vnz = vnz;
        }
        public Student(string firstName, string lastName, string dateOfBirth, string cors, string gro)
    : base(firstName, lastName, dateOfBirth)
        {
            Course = cors;
            Group = gro;
            Faculty = "Фікт";
            Vnz = "ЖДТУ";
        }
        public Student(string firstName, string lastName, string dateOfBirth)
: base(firstName, lastName, dateOfBirth)
        {
            Course = "1";
            Group = "КБ-1";
            Faculty = "Фікт";
            Vnz = "ЖДТУ";
        }
        public Student()
        {
            FirstName = "Tom";
            LastName = "Johns";
            DateOfBirth = "11.02.1999";
            Course = "1";
            Group = "КБ-1";
            Faculty = "Фікт";
            Vnz = "ЖДТУ";
        }
        public override void ShowInfo()
        {
            base.ShowInfo();
            Console.WriteLine($"\nнавчається на {Course} курсі, в групі {Group} ," +
                $" на факультеті {Faculty}, в {Vnz} \n");
        }
    }
}

Ошибка возникает на этом моменте:

Этот объект класса Person, но я объявляю его как Student. Помогите.

Answer 1

Наоборот: это объект типа Student, но Вы объявляете его как Person.

Student stud = new Student();
stud.FirstName = ...;
...
stud.Course = ...;
...
person[n] = stud;
n++;
READ ALSO
TopMost не работает в Windows CE 6.0 (Micros Workstation 5.0)

TopMost не работает в Windows CE 6.0 (Micros Workstation 5.0)

Создаю приложения для терминала Micros Workstation 5 (Windows CE 60)

209
Изменение роли без переавторизации

Изменение роли без переавторизации

У пользователя А несколько ролей, одна из которых "viewer"Удаляю роль:

209
C# авторизация в программе

C# авторизация в программе

Есть статический метод, принимающий значений логина и пароля и возвращающий из базы данных конкретного пользователя

232
Перечислить через запятую в switch значения

Перечислить через запятую в switch значения

В VBNET есть вот такая конструкция:

209