C# 6 - String Interpolation
نویسنده: وحید نصیری
تاریخ: ۱۳۹۴/۰۷/۱۱ ۱۳:۴۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
using System;
namespace CS6NewFeatures
{
class Person
{
public string FirstName { set; get; }
public string LastName { set; get; }
public int Age { set; get; }
}
class Program
{
static void Main(string[] args)
{
var person = new Person { FirstName = "User 1", LastName = "Last Name 1", Age = 50 };
var message = string.Format("Hello! My name is {0} {1} and I am {2} years old.",
person.FirstName, person.LastName, person.Age);
Console.Write(message);
}
}
}
static void Main(string[] args)
{
var person = new Person { FirstName = "User 1", LastName = "Last Name 1", Age = 50 };
var message = $"Hello! My name is {person.FirstName} {person.LastName} and I am {person.Age} years old.";
Console.Write(message);
} var message2 = $"{Environment.NewLine}Test {DateTime.Now}, {3*2}";
Console.Write(message2); var message3 = $"{Environment.NewLine}{1000000:n0} {DateTime.Now:dd-MM-yyyy}";
Console.Write(message3); class MyDateFormatProvider : IFormatProvider
{
readonly MyDateFormatter _formatter = new MyDateFormatter();
public object GetFormat(Type formatType)
{
return formatType == typeof(ICustomFormatter) ? _formatter : null;
}
class MyDateFormatter : ICustomFormatter
{
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (arg is DateTime)
return ((DateTime)arg).ToString("MM/dd/yyyy");
return arg.ToString();
}
}
} static string formatMyDate(FormattableString formattable)
{
return formattable.ToString(new MyDateFormatProvider());
} var message2 = formatMyDate($"{Environment.NewLine}Test {DateTime.Now}, {3*2}");
Console.Write(message2); public static string faIr(IFormattable formattable)
{
return formattable.ToString(null, new CultureInfo("fa-Ir"));
} static string invariant(FormattableString formattable)
{
return formattable.ToString(CultureInfo.InvariantCulture);
} var message0 = $"Hello! My name is {person.FirstName} {{person.FirstName}}"; Console.Write($"{(person.Age>50 ? "old": "young")}"); var x = @$"Time now at UTC {DateTime.UtcNow}"; Error CS1646 Keyword, identifier, or string expected after verbatim specifier: @
using static System.FormattableString;
var number = 11;
var text = Invariant($"{number}"); یک نکتهی تکمیلی: در نگارشهای جدیدتر داتنت، بجای متد Invariant از متد string.Create استفاده کنید
همانطور که پیشتر نیز عنوان شد، formattable stringها، بر اساس فرهنگ جاری سیستم عامل، خروجی را تغییر میدهند. یعنی حاصل نهایی رشتهی "{Id} :value"$ بسته به فرهنگ جاری، میتواند یکبار با اعداد انگلیسی و بار دیگر با اعداد فارسی جایگزین شود. برای عدم مواجه شدن با یک چنین ناهماهنگیهایی، استفاده از متد System.FormattableString.Invariant بر روی یک چنین رشتههایی، توصیه میشد. اکنون (از زمان NET Core 2.1. به بعد)، استفاده از متد string.Create بجای آن توصیه میشود که سرعت بیشتری داشته و همچنین مصرف حافظهی کمتری را نیز به همراه دارد.
همچنین اگر علاقمند هستید تا این موارد را به صورت یک خطا دریافت کنید و مجبور به تغییر آنها شوید، یک سطر زیر را به فایل editorconfig. خود اضافه کنید؛ که مرتبط است به Meziantou.Analyzer:
dotnet_diagnostic.MA0111.severity = error
const string constStrFirst = "FirstStr";
const string summaryConstStr = $"SecondStr {constStrFirst}"; const char a = 'a';
const string constStrFirst = "FirstStr";
const string summaryConstStr = $"SecondStr {constStrFirst} {a}"; // Error CS0133 // The expression being assigned to // 'summaryConstStr' must be constant
namespace CS11Tests;
public static class NewLinesStringInterpolations
{
public static void Test()
{
var month = 8;
var season = $"The season is {month switch
{
>= 1 and <= 3 => "spring",
>= 4 and <= 6 => "summer",
>= 7 and <= 9 => "autumn",
10 or 11 or 12 => "winter",
_ => "Wrong month number",
}}.";
Console.WriteLine(season);
int[] numbers = { 1, 2, 3, 4, 5, 6 };
var message = $"The reversed even values of {nameof(numbers)} are {string.Join(", ",
numbers.Where(n => n % 2 == 0).Reverse())}.";
Console.WriteLine(message);
}
} var text = string.Format("Format one value: {0}", 42);private static readonly CompositeFormat StaticField = CompositeFormat.Parse("Format one value: {0}");
var text = string.Format(StaticField, 42);dotnet_diagnostic.CA1863.severity = error