String Interpolation with format variable

后端 未结 6 2005
心在旅途
心在旅途 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:50

    No, you can't use string interpolation with something other than a string literal as the compiler creates a "regular" format string even when you use string interpolation.

    Because this:

    string name = "bar";
    string result = $"{name}";
    

    is compiled into this:

    string name = "bar";
    string result = string.Format("{0}", name);
    

    the string in runtime must be a "regular" format string and not the string interpolation equivalent.

    You can use the plain old String.Format instead.

提交回复
热议问题