字符串插值的演变

发布日期:2026-07-14 02:39:04  来源 : 杭州电子商务研究院    浏览量 :0
杭州电子商务研究院 发布日期:2026-07-14 02:39:04  
0

介绍

在任何编程语言中,将数据打印到控制台都是一项常见任务。您可以打印简单的状态消息或特定操作的结果,这并不重要。重要的是您的打印语句有多灵活。它如何适应程序流程也很重要。例如,刚开始使用 C# 的人通常会做类似下面的例子。他们得到两个变量的总和并将结果打印到控制台。

      int x = 10;
int y = 20;
int z = x + y;
Console.Write("The sum of " + x + " and " + y + " is " + z);
    

结果是:

      The sum of 10 and 20 is 30
    

这很好,它完成了工作。但是,它缺乏 C# 提供的优雅和利用功能。本指南将向您展示如何在 C# 中使用字符串插值,并详细介绍这方面的最新和最好的功能。

字符串插值可以使用三种类型的变量替换。

  1. 数组访问
  2. 表达式
  3. 方法调用

字符串插值

字符串插值中最重要的方面是$字符。这个字符会通知编译器即将编译的特殊字符串类型。让我们看一个简单的例子。

      string where = "Pluralsight";
string what = "written guides";
Console.WriteLine($"The {what} at {where} are awesome!");
    

这在我们的控制台上给出了以下输出!

      The written guides at Pluralsight are awesome!
    

您可以看到它的优雅,以及缺少+字符来连接变量和我想要打印的字符。

基本语法如下。

`` `插值 [,alignment][:formatString]

      This means that you can either specify a spacing definition, which means you want to have *X* number of characters before the interpolated string, or you can specify a formatter. The formatter comes in handy when you are dealing with, for example, dates. You have a date object and you want to have different formats on the output throughout your entire application, based on the method calls or the section you are currently residing at.

### Interpolation with Array Elements

String interpolation allows you to handle arrays and their items as input for the action.
Let's take a look at the following example.

```csharp
int [] even = {2, 4, 6, 8, 10};
string interpolated = $"These are the even numbers {even[0]}, {even[1]}, {even[2]}, {even[3]}!";
Console.WriteLine($"{interpolated}");
    

给出以下输出。插值字符串的插值。

      These are the even numbers 2, 4, 6, 8!
    

索引到错误的不存在元素将导致异常!插值可以嵌套到第 n 级;您可以创建的插值层数没有限制!

使用表达式进行插值

虽然您可以在插值中使用任意运算符,但您需要考虑一些简单的规则。但您可以使用这种方法做几乎任何您想做的事情。让我们看一个例子。

      int y = 10;
int x = 30;
Console.WriteLine($"{x} + {y} = {x + y}");
Console.WriteLine($"{x} - {y} = {x - y}");
Console.WriteLine($"{x} * {y} = {x * y}");
Console.WriteLine($"{x} / {y} = {x / y}");
    

这给了我们以下输出!

      30 + 10 = 40
30 - 10 = 20
30 * 10 = 300
30 / 10 = 3
    

当表达式求值为空时,结果为空字符串,又称String.Empty字符。如果求值不为空,则调用结果类型的ToString方法。

通过方法调用进行插值

字符串插值的第三个方面也是最复杂的方面是通过方法调用及其返回值来完成的。最重要的是要有一个可以插值的方法返回值,仅此而已。

      static int FourthPower(int x)
	{ return x * x * x * x; }
static void Main(string[] args)
{
    int x = 2;
    Console.WriteLine($"The {x} to the fourth power equals to: {FourthPower(x)}");
}
    

结果如下:

      The 2 to the fourth power equals 16
    

带对齐的插值

此示例将向您展示如何利用从左到右对齐的插值。当您想要创建格式漂亮的表格输出并保留您心中的结构时,这会非常有用。

      var workers = new Dictionary<string, string>()
{
    ["John Doe"] = "DevOps Engineer",
    ["Jane Doe"] = "Network Architect",
    ["William Doe"] = "Product Manager"
};
Console.WriteLine("Colleague and Position list!");
Console.WriteLine("");
Console.WriteLine($"|{"Worker",-15}|{"Position",20}|");
foreach (var title in workers)
    Console.WriteLine($"|{title.Key,-15}|{title.Value,20}|");
    

我们创建了一个基于字符串的字典变量。然后使用三个工人的键值对初始化值。我们有 print 语句来命名我们的表。然后提供名为WorkerPosition 的列名。第一列是左对齐的,第二列是右对齐的。

为插值的对齐参数指定负值会使插值字符串左对齐。正值会使它右对齐!

我们得到的输出是一个带有名称的美观的表格。

      Colleague and Position list!

|Worker         |            Position|
|John Doe       |     DevOps Engineer|
|Jane Doe       |   Network Architect|
|William Doe    |     Product Manager|
    

结论

我希望本指南能让您了解字符串插值如何帮助您轻松开发应用程序,以及提高透明度和可维护性。与实现类似结果的旧方法相比,这是一个巨大的进步,我鼓励您将其纳入您的应用程序中。总而言之,字符串插值是开发人员工具箱中非常方便的工具。

以上内容来自杭州电子商务研究院推送
分享到:

长按或扫码识别 分享给好友

长按或扫码识别 分享给好友
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据