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

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


var name = "world";
string str1 = string.Format("hello {0}",name); //等于 var str1 = $"hello {name}";
IFormattable str2 = FormattableStringFactory.Create("hello {0}",name);
FormattableString str3 = FormattableStringFactory.Create("hello {0}",name);
  • IFormattable 从.net Framwork 1 时代就有了,只有一个ToString方法,可以传入IFormatProvider来控制字符串的格式化。今天的主角不是他。
  • FormattableString 伴随Interpolated Strings引入的新类。

    FormattableString 是什么?

    先看一段代码

    
    var name = "world";
    FormattableString fmtString = $"hello {name}";
    Console.WriteLine(fmtString.ArgumentCount); //1
    Console.WriteLine(fmtString.Format); //hello {0}
    foreach (var arg in fmtString.GetArguments())
    {
     Console.WriteLine(arg); //world
     Console.WriteLine(arg.GetType()); //System.String
    }

    可以看出FormattableString保存了Interpolated Strings的所有信息,所以EF Core 2.0能够以参数化的方式来执行SQL了。

    EF Core 中的注意事项

    因为隐式转换的原因,在使用EF Core的FromSql 方法和 ExecuteSqlCommand方法时,需要特别小心。一不留神就会调入陷阱。

    
    var city = "London";
    
    using (var context = CreateContext())
    {
     //方法一,非参数化
     var sql = $" SELECT * FROM Customers WHERE City = {city}";
     context.Customers.FromSql(sql).ToArray();
    
     //方法二,参数化
     context.Customers.FromSql($" SELECT * FROM Customers WHERE City = {city}").ToArray();
    
     //方法三,参数化
     FormattableString fsql = $" SELECT * FROM Customers WHERE City = {city}";
     context.Customers.FromSql(fsql).ToArray();
    
     //方法四,非参数化
     var sql = " SELECT * FROM Customers WHERE City = @p0";
     context.Customers.FromSql(sql, city).ToArray();
    
    }