C# 6.0 内插字符串(Interpolated Strings )的使用方法

2020-01-05 09:54:20刘景俊

看Interpolated Strings之前,让我们先看EF Core 2.0 的一个新的特性:String interpolation in FromSql and

ExecuteSqlCommand。


var city = "London";

using (var context = CreateContext())
{
 context.Customers
  .FromSql($@"
   SELECT *
   FROM Customers
   WHERE City = {city}")
  .ToArray();
}

SQL语句以参数化的方式执行,所以是防字符串注入的。


@p0='London' (Size = 4000)

SELECT *
FROM Customers
WHERE City = @p0

一直认为Interpolated Strings只是String.Format的语法糖,传给FromSql的方法只是一个普通的字符串,已经移除了花括号,并把变量替换成了对应的值。FromSql获取不到变量信息,怎么实现参数化查询的呢? OK,让我们从头看起吧。

什么是内插字符串 (Interpolated Strings)

内插字符串是C# 6.0 引入的新的语法,它允许在字符串中插入表达式。


var name = "world";
Console.WriteLine($"hello {name}");

这种方式相对与之前的string.Format或者string.Concat更容易书写,可读性更高。就这点,已经可以令大多数人满意了。事实上,它不仅仅是一个简单的字符串。

内插字符串 (Interpolated Strings) 是什么?

用代码来回答这个问题:


var name = "world";
string str1 = $"hello {name}"; //等于 var str1 = $"hello {name}";
IFormattable str2 = $"hello {name}";
FormattableString str3 = $"hello {name}";

可以看出,Interpolated Strings 可以隐式转换为3种形式。实际上式编译器默默的为我们做了转换: