重写父类的ToString

我们任何对象调用ToString的时候,打出来的都是这个类的命名空间的名字

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

namespace 重写ToString方法
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            Console.WriteLine(p.ToString());
            Console.ReadKey();
        }
    }
    public class Person
    {

    }
}

 

 

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

namespace 重写ToString方法
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            Console.WriteLine(p.ToString());
            Console.ReadKey();
        }
    }
    public class Person
    {
        public override string ToString()
        {
            return "hello world!";//这里重写了,只重写了Person类的ToString方法,然后Person类打出来的ToString就是hello world,但是其他类还是显示命名空间的名字
        }
    }
}

 

posted @ 2021-08-10 11:32  静态类  阅读(93)  评论(0编辑  收藏  举报