自定義格式化字串
阿新 • • 發佈:2020-10-09
----------------------------------------------主程式
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespaceConsoleApplication4 { classProgram { staticvoidMain(string[]args) { //自定義格式化字串 Voctorv=newVoctor(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
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespaceConsoleApplication4 { //自定義格式化字串類或結構必須實現IFormattable介面 publicclassVoctor:IFormattable { doublex,y,z; publicVoctor(doubled1,doubled2,doubled3) { this.x=d1; this.y=d2; this.z=d3; } //format表示傳遞的說明符,例如N(不用考慮formatProvider) publicstringToString(stringformat,IFormatProviderformatProvider) { if(format==null) { returnToString(); } //不區分大小寫 stringformatUpper=format.ToUpper(); switch(formatUpper) { case"ZHANG": return"Zhang:"+ToString(); case"LIU": return"Liu:"+ToString(); default: returnToString(); } } publicoverridestringToString() { returnstring.Format("({0},{1},{2})",x,y,z); } } }
轉載於:https://blog.51cto.com/962410314/1541283