What is the optional argument in C# interpolated string for?

后端 未结 2 910
暗喜
暗喜 2021-01-03 18:42

Interpolated strings is one of the new features of C# 6.0.

According to MSDN, the syntax of the embedded C# expressions can contain an optional, comma-separated val

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-03 19:00

    The number is the alignment, documented in the Alignment Component here.

    The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative.

    In your example, alignment will pad the p.ProcessName with spaces if it is less than 5 characters long. Where string length is less than the absolute value of alignment (like in your example), alignment has no effect.

    Example

    var text = "MyText";
    Console.WriteLine($"x{text}x");
    Console.WriteLine($"x{text, 3}x");
    Console.WriteLine($"x{text, 10}x");
    Console.WriteLine($"x{text, -10}x");
    

    Result

    xMyTextx
    xMyTextx
    x    MyTextx
    xMyText    x
    

提交回复
热议问题