小赖子的英国生活和资讯

C# 6.0 的新语法之一 – 字符串 插值 Interpolation

阅读 桌面完整版

(VS2015) C# 6.0 有很多新语法 比如这个字符串插值则是我比较喜欢的之一. 这替代以前的 string.format 方法. 比如下面的程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System;
 
namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            int v = 1;
            Console.WriteLine(string.Format("v = {0}", v));
            Console.ReadLine();
        }
    }
}
using System;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            int v = 1;
            Console.WriteLine(string.Format("v = {0}", v));
            Console.ReadLine();
        }
    }
}

RESHARPER 插件string.format 变成灰色的 并提示说是冗余的. 当然它还有一键修复的功能 点击小黄灯泡就会自动将程序变成:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System;
 
namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            int v = 1;
            Console.WriteLine($"v = {v}");
            Console.ReadLine();
        }
    }
}
using System;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            int v = 1;
            Console.WriteLine($"v = {v}");
            Console.ReadLine();
        }
    }
}

可以看到 参数直接写在字符串里 但是要在字符串前面加入 $ 符号. 这个类似 @ 用于不转义一样. 这样的好处是不需要对应参数是第几个 更简单直接明了.

csharp

英文: https://helloacm.com/c-6-0-new-feature-string-interpolation/

强烈推荐

微信公众号: 小赖子的英国生活和资讯 JustYYUK

阅读 桌面完整版
Exit mobile version