Framework:.NET Framework 4.6 ( 又稱 .NET 2015 ) C#6.0
開始前要先釐清 CLR、.NET、C#、Visual Studio、ASP.NET 各版本之間的關係 ,人腦記憶力有限,當不清楚自己已安裝的版本,可以使用PowerShell 查詢主機目前安裝的 .NET 版本,
以下文字擷取自黑暗大的C# Interpolated Strings 字串插值
場景移到 C#,字串內含換行符號靠 @"…." (String Literal,字串常值)可輕鬆擺平,是 .NET 1.1 時代就有的老東西。
TypeScript 在字串裡用 ${variable_name} 直接穿插變數的做法稱為 String Interpolation,
C# 傳統上靠 string.Format("Hello, {0}", userName) 實現(術語為 Composite Format,複合格式)。
C# 6.0 起新加入 Interpolated Strings(字串插值)特性,不需再用 string.Format() 就可直接混搭文字與變數。
Code example
class Program
{
static void Main(string[] args)
{
//插入變數,比照string.Format可加上:n0,:yyyy-MM-dd等格式規範
var userName = "Ben.Tseng";
var score = 32767;
var result = $"{userName}'s score is {score:n0}. {DateTime.Today:yyyy-MM-dd}";
Console.WriteLine(result);
//指定固定寬度
var items = new string[] { "Notebook", "Phone", "PC" };
foreach (var item in items)
{
Console.WriteLine($"{item, 12} checked.");
}
//加入邏輯運算,與@""混合使用以支援換行,用{{、}}代表{、}
Console.WriteLine($@"
{{ {score} + 1 = {score + 1} }}
{score} is {(score % 2 == 0 ? "even":"odd")}
");
Console.Read();
}
}
使用Visual Studio 2015,結果如下
C# 6.0 的Interpolated Strings,跟TypeScript 的Template String 很類似, 輸出內嵌動態資料 HTML 時非常好用。
var userName: string = "Ben.Tseng"; var iconUrl: string = "/imgs/runner.gif"; var html = `Hello, ${userName}! <img src="${iconUrl}/>`; alert(html);
參考資料
C# 字串內含換行符號靠 @"…." (String Literal,字串常值)
C# 術語為 Composite Format,複合格式
C# 6.0 起新加入 Interpolated Strings(字串插值)
TypeScript 的Template String
黑暗執行緒的C# Interpolated Strings 字串插值
沒有留言:
張貼留言