自定义格式化字符串

发布时间:2020-07-12 18:46:29 作者:1473348968
来源:网络 阅读:397

----------------------------------------------主程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            //自定义格式化字符串
            Voctor v = new Voctor(3d, 4d, 5d);
            Console.WriteLine("{0:zhang}", v);//Zhang:(3,4,5)
            Console.WriteLine("{0:liu}", v);//Liu:(3,4,5)
            Console.ReadKey();
        }
    }
}

----------------------------------------------Voctor.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
    //自定义格式化字符串类或结构必须实现IFormattable接口
    public class Voctor : IFormattable
    {
        double x, y, z;

        public Voctor(double d1, double d2, double d3)
        {
            this.x = d1;
            this.y = d2;
            this.z = d3;
        }
        //format表示传递的说明符,例如N(不用考虑formatProvider)
        public string ToString(string format, IFormatProvider formatProvider)
        {
            if (format == null)
            {
                return ToString();
            }
            //不区分大小写
            string formatUpper = format.ToUpper();
            switch (formatUpper)
            {
                case "ZHANG":
                    return "Zhang:" + ToString();
                case "LIU":
                    return "Liu:" + ToString();
                default:
                    return ToString();
            }
        }
        public override string ToString()
        {
            return string.Format("({0},{1},{2})", x, y, z);
        }
    }
}

 

自定义格式化字符串

自定义格式化字符串

 

 

推荐阅读:
  1. python format格式化字符串传变量
  2. 使用golang怎么格式化字符串

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

字符串 格式 格式字符串

上一篇:初学C#,关于C#的简单入门

下一篇:ASA透明防火墙_06

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》