微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在C#中使用继承时,无法打印数组的值

如何解决在C#中使用继承时,无法打印数组的值

我正在尝试使用继承和多态性从数组中进行打印...等

该练习是一个从Person类继承而来的学生和教师类,但是通过覆盖两个类中的print方法,它们显示出不同的结果。教师班从字符串变量打印,而学生班从字符串变量和字符串数组打印。我能够打印所有内容,但我打印字符串数组的部分却得到了System.String [],据我了解,这是因为它打印的是对象的名称而不是值。我尝试重写To.String方法以将其传递给printDetails方法,但是由于我的printDetails方法具有返回类型void,因此我无法做到这一点。

下面是我的代码供参考:

Program.cs:


namespace Task3
{
    class Program
    {
        static void Main(string[] args)
        {
           
            var people = new List<Person>();

            string[] subjects = { "Math","Science","English" };
            string studentName = "Sue";

            Student student = new Student(studentName,subjects);
            people.Add(student);
         
            
            string faculty = "Computer Science";
            string teacherName = "Tim";

            Teacher teacher = new Teacher(teacherName,faculty);
            people.Add(teacher);


            foreach (var element in people)
            {
                element.PrintDetails();
            }

            Console.ReadKey(); 
        }
    }
}

Person.cs:

namespace Task3
{
    public abstract class Person
    {
        protected string _name;
        public Person(){}

        public Person(string name)
        {
            _name = name;
        }

        public abstract void PrintDetails();
    }
}

Student.cs:

namespace Task3
{
    public class Student : Person
    {
        private string[] _subjects;

        public Student(string name,string[] subjects) : base(name)
        {
            
            _subjects = subjects;
        }

        public override void PrintDetails()
        {
            Console.WriteLine("Hi my name is " + _name + " and I am studying " + _subjects);        
        }        
    }
}

Teacher.cs:

namespace Task3
{
    public class Teacher : Person
    {
        private string _faculty;

        public Teacher(string name,string faculty) : base(name)
        {

            _faculty = faculty;
        }

        public override void PrintDetails()
        {
            Console.WriteLine($"Hi my name is {_name} and I teach in the {_faculty} faculty");
        }
    }
}

下面是我得到的输出,我应该得到的输出

enter image description here

Output in the console

解决方法

您的PrintDetails()方法无需任何格式化即可打印数组(因此它只是打印数组类型)

使用string.Join打印以逗号分隔的数组

public override void PrintDetails()
{
   Console.WriteLine("Hi my name is " + _name + " and I am studying " + string.Join(",",_subjects));        
} 

应该这样做。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。