c#6 字符串 插值_【译】C#中优雅的字符串处理,特殊插值符

开发程序过程中,去处理格式化的内容输出是很常见的,无论你开发控制台程序,Web应用还是移动开发都有类似的场景。

C#6中微软引入了新的字符串操作符($)帮助开发者们简单的操作字符串文本。

本文中,我用几个例子帮助理解这个操作符。

我们想下这个例子,两个数相加并打印它们的结果。非常简单的例子,下面是C#中老的实现方式

打开https://try.dot.net/ 这个C#的在线编译工具,可以看运行结果。 后面的例子都可以复制内容编辑器,然后点Run查看运行结果。

using System;

using System.Collections.Generic;

using System.Linq;

public class Program

{

public static void Main()

{

int a = 2, b = 3, sum = a + b;

Console.Write("The sum of " + a + " and " + b + " is " + sum);

}

}

这个代码输出如下内容

The sum of 2 and 3 is 5

我相信大多数人不会同意这个代码,因为字符拼接总是痛苦的,有更好的选择。让我们使用 String.format 来组织代码

using System;

using System.Collections.Generic;

using System.Linq;

public class Program

{

public static void Main()

{

int a = 2, b = 3, sum = a + b;

Console.Write(String.Format("The sum of {0} and {1} is {2}", a, b, sum));

}

}

对于大多数开发人员来说,这是首选方法(在 C# 6 之前)。它生成的输出与前面的语句完全相同。

我相信,当处理相对较大的字符串和更多的参数时,这也是痛苦的。参数的顺序和在代码块中的使用总是从开发人员那里窃取一些时间。插值特殊字符 ($) 可帮助开发人员以更好的方式编写代码。

请考虑以下示例。

using System;

using System.Collections.Generic;

using System.Linq;

public class Program

{

public static void Main()

{

int a = 2, b = 3, sum = a + b;

Console.Write($"The sum of {a} and {b} is {sum}");

}

}

此代码还会生成与前两个完全相同的结果。您会注意到代码是多么容易和可读。$ 符号使字符串成为可插值的字符串。解析后,大括号 ({}) 内的表达式将被相应的表达式结果替换。酷!。

下面的示例。

using System;

using System.Collections.Generic;

using System.Linq;

public class Program

{

public static void Main()

{

Console.Write($"Today is {DateTime.Now.ToShortDateString()}");

}

}

会产生如下结果

Today is 8/10/2019

您可以将 $ 和 + 运算符组合在一个字符串中。请参阅以下示例

using System;

using System.Collections.Generic;

using System.Linq;

public class Program

{

public static void Main()

{

String Username = "Mark Smith";

Decimal amount = 89.560m;

Console.Write($@"

Dear {Username},Your Total Due for this month is {amount}.

Please settle the amount at the earliest.

");

}

}

此外,还可以指定字符串应保留的最小空格数。默认情况下,文本右对齐,对齐参数的负值将使其左对齐。

下面的示例。

using System;

using System.Collections.Generic;

using System.Linq;

public class Program

{

public static void Main()

{

Console.Write($@"

 
 

9 x 1 = {9 * 1,2}

9 x 2 = {9 * 2,2}

9 x 3 = {9 * 3,2}

");

}

}

输出的结果是

9 x 1 = 9

9 x 2 = 18

9 x 3 = 27

请参阅结果的对齐方式 (9,18,27),它是右对齐。如果使用 -2,它将保持左对齐状态。

还可以使用格式表达式设置表达式的格式。请考虑以下示例

using System;

using System.Collections.Generic;

using System.Linq;

public class Program

{

public static void Main()

{

Console.Write($"Today is {DateTime.Now: yyyy MM dd dddd}");

}

}

将会产生如下结果

Today is 2019 08 26 Monday

总结

插值特殊字符($)将帮助开发人员以更简单、更灵活的方式操作字符串。

作者:Dino

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值