Multiline C# interpolated string literal

前端 未结 3 759
礼貌的吻别
礼貌的吻别 2020-12-10 00:29

C# 6 brings compiler support for interpolated string literals with syntax:

var person = new { Name = \"Bob\" };

string s = $\"Hello, {person.Name}.\";


        
相关标签:
3条回答
  • 2020-12-10 00:53

    Personally, I just add another interpolated string using string concatenation

    For example

    var multi  = $"Height     : {height}{Environment.NewLine}" +
                 $"Width      : {width}{Environment.NewLine}" +
                 $"Background : {background}";
    

    I find that is easier to format and read.

    This will have additional overhead compared to using $@" " but only in the most performance critical applications will this be noticeable. In memory string operations are extremely cheap compared to data I/O. Reading a single variable from the db will take hundreds of times longer in most cases.

    0 讨论(0)
  • 2020-12-10 00:56

    You can combine $ and @ together to get a multiline interpolated string literal:

    string s =
    $@"Height: {height}
    Width: {width}
    Background: {background}";
    

    Source: Long string interpolation lines in C#6 (Thanks to @Ric for finding the thread!)

    0 讨论(0)
  • 2020-12-10 01:05

    I'd probably use a combination

    var builder = new StringBuilder()
        .AppendLine($"Width: {width}")
        .AppendLine($"Height: {height}")
        .AppendLine($"Background: {background}");
    
    0 讨论(0)
提交回复
热议问题