String Interpolation with format variable

后端 未结 6 1995
心在旅途
心在旅途 2020-11-27 22:08

I can do this:

var log = string.Format(\"URL: {0}\", url);

or even like this

var format = \"URL: {0}\";
...
var log = strin         


        
6条回答
  •  隐瞒了意图╮
    2020-11-27 22:53

    String interpolation is a compiler, not library, feature.

    The holes are not names, but expressions:

    var r = new Rectangle(5, 4);
    var s = $"area: {r.Width + r.Heigh}":
    

    How would you do that for localization, as you intend to?

    Even r only exists at compile time. In IL it's just a position on the method's variable stack.

    I've done what you intend to do for resources and configuration files.

    Since you can only have a finite set of "variables" to substitute, what I did was have an array (or dictionary, if you prefer) and use a regular expression to replace the names in the holes with its index. What I did even allowed for format specifiers.

提交回复
热议问题