String interpolation inside string interpolation

依然范特西╮ 提交于 2021-01-20 12:31:09

问题


Is it possible to have a variable with a string format that you would like interpolated.

public class Setting
{
    public string Format { get; set; }
}


var setting = new Setting { Format = "The car is {colour}" };
var colour = "black";
var output = $"{setting.Format}";

Expected output

"The car is black".


回答1:


You can't do that. String interpolation is a purely compile-time feature.




回答2:


No you can't do that, but you can achieve the same with a slightly different approach, that I've come to like:

public class Setting
{
    public Func<string, string> Format { get; set; }
}

then you can pass your string argument to Format:

var setting = new Setting { Format = s => $"The car is {s}" };
var output = setting.Format("black");



回答3:


Why not?
First of all, you can't use a local variable before declaring it in C#. So First declare the colour before using it. Then "interpolate" the string assigned to Format and you are done.

var colour = "black";
var setting = new Setting { Format = $"The car is {colour}" };
var output = $"{setting.Format}";
Console.WriteLine(output);

Output:

The car is black.




回答4:


You can do a slight alteration on it, like the following:

public class Setting
{
    public string Format
    { 
        get
        {
            return String.Format(this.Format, this.Colour);
        }
        set
        {
            Format = value;
        }
    }

    public string Colour { get; set; }
}


var setting = new Setting { Format = "The car is {0}", Colour = "black" };

Then the output will be "The car is black".

I haven't tested this code.



来源:https://stackoverflow.com/questions/33829410/string-interpolation-inside-string-interpolation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!