string name = "Mark"; var date = DateTime.Now; // Composite formatting: Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date); // String interpolation: Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now."); // Both calls produce the same output that is similar to: // Hello, Mark! Today is Wednesday, it's 19:40 now.
Web应用
// GET: /HelloWorld/Welcome/ // Requires using System.Text.Encodings.Web; public string Welcome(string name, int numTimes = 1) { return HtmlEncoder.Default.Encode($"Hello {name}, NumTimes is: {numTimes}"); }
前面的代码:
使用 C# 可选参数功能指示,未为 numTimes 参数传递值时该参数默认为 1。
使用 HtmlEncoder.Default.Encode 防止恶意输入(例如通过 JavaScript)损害应用。
在 $"Hello {name}, NumTimes is: {numTimes}" 中使用内插字符串。
可以设置格式显示
详见:https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/tokens/interpolated
aspnetcore-5.0官方教程:https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-mvc-app/adding-controller?view=aspnetcore-5.0&tabs=visual-studio