-->

C# FormattableString concatenation for multiline i

2019-08-21 09:15发布

问题:

In C#7, I'm trying to use a multiline interpolated string for use with FormttableString.Invariant but string concatenation appears to be invalid for FormttableString.

Per the documentation: A FormattableString instance may result from an interpolated string in C# or Visual Basic.

The following FormttableString multiline concatenation does not compile:

using static System.FormattableString;
string build = Invariant($"{this.x}" 
                       + $"{this.y}"
                       + $"$this.z}");

Error CS1503 - Argument 1: cannot convert from 'string' to 'System.FormattableString'

Using an interpolated string without concatenation does compile:

using static System.FormattableString;
string build = Invariant($"{this.x}");

How do you implement multiline string concatenation with the FormattableString type?

(Please note that FormattableString was added in .Net Framework 4.6.)

回答1:

The Invariant method is expecting the parameter of FormattableString type. In your case, the parameter $"{this.x}" + $"{this.y}" becomes "string" + "string' which will evaluate to string type output. That's the reason you are getting the compile error as Invariant is expecting the FormattableString and not string.

You should try this for single line text -

public string X { get; set; } = "This is X";
public string Y { get; set; } = "This is Y";
public string Z { get; set; } = "This is Z";
string build = Invariant($"{this.x} {this.y} {this.z}");

Output -

This is X This is Y This is Z

And to implement multiline interpolation, you can build the FormattableString like below and then use the Invarient.

FormattableString fs = $@"{this.X}
{this.Y}
{this.Z}";
string build = Invariant(fs);

Output -

This is X

This is Y

This is Z