.NETdotNET

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

2019-08-26  本文已影响0人  Dino

开发程序过程中,去处理格式化的内容输出是很常见的,无论你开发控制台程序,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($@"<pre>Dear {Username},Your Total Due for this month is {amount}.

        Please settle the amount at the earliest.

        </pre>");
  }
}

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

下面的示例。


using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
  public static void Main()
  {
    
        
        Console.Write($@"<pre>

        9 x 1 = {9 * 1,2}

        9 x 2 = {9 * 2,2}

        9 x 3 = {9 * 3,2}

        </pre>");
  }
}

输出的结果是

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

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

上一篇下一篇

猜你喜欢

热点阅读