zoukankan      html  css  js  c++  java
  • C# 如何重写ToString方法

    Demo1:加上价格标签

    class Program
        {
            public decimal price { get; set; }
            static void Main(string[] args)
            {
                Program p = new Program();
                p.price = 25;
                Console.WriteLine(p.ToString());
                Console.ReadKey();
            }

            public override string ToString()
            {
                return "$"+price.ToString();
            }
        }

    Demo2:修改时间的输出格式

     public DateTime time { get; set; }
            static void Main(string[] args)
            {
                Program p = new Program();

                p.time = DateTime.Now;

                Console.WriteLine(p.ToString());

                Console.ReadKey();
            }

            public override string ToString()
            {
                return string.Format("{0}年{1}月{2}日",time.Year,time.Month,time.Day);
            }

    Demo3:

    public override string ToString()
    {
    StringBuilder builder = new StringBuilder(16);
    bool firstTime = true;
    foreach (T item in this)
    {
    if (firstTime)
    {
    firstTime = false;
    }
    else
    {
    builder.AppendLine();
    }
    builder.Append(item);
    }
    return builder.ToString();
    }

    高山仰止, 景行行止。 四牡鲱鲱, 六辔如琴。 觏尔新婚, 以慰我心。
  • 相关阅读:
    DNS 截持模拟及环境搭建
    Ant、Gradle、Python三种打包方式的介绍
    oc/c/c++混编老文,写的很好,mark
    好文!关于iOS下的正则表达式实战案例
    Java设计模式——享元模式
    Java 消息机制之回调详解
    windows版爬取csdn
    14.6.2 Configuring InnoDB for Read-Only Operation
    dump iot表
    heap表按字符串和数值型排序规则
  • 原文地址:https://www.cnblogs.com/davidshi/p/3291646.html
Copyright © 2011-2022 走看看