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