C# 中类重写 ToString 方法

一,C# 中的每个类或结构都隐式继承 Object 类。因此,C# 中的每个对象都会获得 ToString 方法,此方法返回该对象的字符串表示形式。而同时在Object 中的ToString是虚方法则可以被重写。下面是重写前和后的比较:

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

namespace OverToString
{
    class Program
    {
        static void Main(string[] args)
        {
            Demo d = new Demo("重写输出");
            Demo1 d1 = new Demo1("原始输出");
            Console.WriteLine(d); //输出:重写输出,重写ToString之后输出你重写的内容
            Console.WriteLine(d1); //输出d1的类型:OverToString.Demo1,就是如果没有重写是默认输出值得类型
        }
    }
    public class Demo
    {
        public Demo(string str)
        {
            this.Str = str;
        }
        public override string ToString()
        {
            return this.Str.ToString();
        }
        public string Str { get; set; }

    }
    public class Demo1
    {
        public Demo1(string str)
        {
            this.Str = str;
        }
        
        public string Str { get; set; }

    }
}
原文地址:https://www.cnblogs.com/May-day/p/6520024.html