當前位置:
首頁 > 知識 > C 6.0 內插字元串 (Interpolated Strings)

C 6.0 內插字元串 (Interpolated Strings)

講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種形式。實際上式編譯器默默的為我們做了轉換:

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(ftmSring.ArgumentCount); //1
Console.WriteLine(ftmSring.Format); //hello {0}
foreach (var arg in ftmSring.GetArguments)
{
Console.WriteLine(arg); //world
Console.WriteLine(arg.GetType); //System.String
}

可以看出FormattableString保存了Interpolated Strings的所有信息,所以EF Core 2.0能夠以參數化的方式來執行SQL了。


ES2015 中的Tagged template literals

熟悉ES2015的同學可以看看Javascript中的實現,Tagged template literals,這和Interpolated Strings 非常類似。

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 科技優家 的精彩文章:

程序員的自我修養三目標文件里有什麼
Http跨域時的Option請求
ARP與RARP協議及arp腳本

TAG:科技優家 |

您可能感興趣

ubuntu16.04通過Chrome搭建Postman環境
爆改賓士G-CLASS!Brabus殺手鐧850 6.0 Biturbo Widesta!
開源PaaS Rainbond v3.6.0:提供service mesh微服務架構開箱即用
鎚子T2/堅果Pro 2等推送Smartisan OS v6.0
Ubuntu16.04+Python2.7環境下facenet的安裝
Nintendo Switch系統更新6.0.0版本的數據挖掘
搭載 Smartisan OS 6.0,堅果 TNT Station 成色幾何?
ubuntu16.04安裝TensorFlow的正確步驟
Switch Online 服務正式上線,任天堂推送 Switch 6.0.0 更新
鎚子發布Smartisan OS v6.0系統更新
微星 Afterburner 4.6.0 beta10發布
Hyper Boost加持 ColorOS 6.0系統發布:主打快穩省
VirtualBox 6.0正式發布:支持虛擬機導出至Oracle Cloud架構
哈希日報:支付服務公司Circle將以4億美元收購P網;Bitcoin Core 0.16.0版本正式發布全面支持segwit
Ubuntu16.04+python3+IDLE安裝
iStat Menus 6.00 超強大的Mac系統監視工具
堅果Pro 2s將搭載SmartisanOS 6.6.0,網友表示很期待
Cherry MX Board 6.0 RGB鍵盤體驗
基於Ubuntu 16.04配置TensorFlow-GPU 1.9.0深度學習環境
輔助增強工具Office Tool Plus發布v6.0正式版