독개

[C#] ToString()의 활용

by #독개#
            Student student = new Student();
            Console.WriteLine(student.ToString());//출력 : 네임스페이스명.student
            Console.WriteLine(student);           //출력 : 네임스페이스명.student

Console.WriteLine은 기본적으로 class를 매개변수로 받으면, 그 class안에 ToString()함수를 반환하게 설계되어 있다

이를 조금 활용해서 나의 클래스들에 ToString을 재정의 해주면 원하는 값을 출력할 수 있다

직접 정의로 이동해서 보았다

console WirteLine의 내부


상속관계
    internal class Human
    {
        public string name { get; set; }
        public string fun_Human()
        {
            return "휴먼함수호출";
        }
    }

    internal class Student : Human
    {
        public int classID { get; set; }
        public override string ToString()
        {
            return $"이름 : {name} , 학번: {classID} , {base.fun_Human()} ";
            //this는 자기자신, base는 부모
        }
호출

호출함수 이미지

 

블로그의 정보

독한 개발자

#독개#

활동하기