1. 程式人生 > 實用技巧 >自定義格式化字串

自定義格式化字串

----------------------------------------------主程式

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);
}
}
}

wKioL1PwcmOCKFyhAAExNxa1Re8772.jpg

wKiom1PwcUujTpsSAAHniKn0q8c332.jpg

轉載於:https://blog.51cto.com/962410314/1541283