C#字符串格式化三种方式

C#字符串格式化三种方式


//$字符串格式化,用对象名称定位(类似模板语言,可以对参数进行逻辑运算,复杂度高,编译时无法检查错误导致运行时异常)
string name = "Horace";
int age = 34;
Console.WriteLine($"He asked, \"Is your name {name}?\", but didn't wait for a reply :-{{");
Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");

________
//String.Format字符串格式化,用数字下标定位(推荐)
string formatString = "    {0,10} ({0,8:X8})\n And {1,10} ({1,8:X8})\n  = {2,10} ({2,8:X8})";
int value1 = 16932;
int value2 = 15421;
string result = String.Format(formatString, value1, value2, value1 & value2);
Console.WriteLine(result );

_____________
//Console.WriteLine直接输出时格式化,用数字下标定位(貌似有参数个数限制,不能超过11个参数)
Console.WriteLine("Tip total/rate:\t{0,8:c} ({1:p1})", tip, tipRate);

你可能感兴趣的:(C#,字符串格式化)