Joh*_*tos 6 c# string-formatting formattablestring
假设,在 C# 程序中,我的 中有以下几行app.config:
<appSettings>
<add key="FormattedString" value="{greeting}, {name}." />
</appSettings>
Run Code Online (Sandbox Code Playgroud)
而且,在我的代码中,我使用它如下:
private void doStuff()
{
var toBeFormatted = ConfigurationManager.AppSettings["FormattedString"];
string greeting = @"Hi There";
string name = @"Bob";
}
Run Code Online (Sandbox Code Playgroud)
我想将toBeFormatted变量用作 aFormattableString以便能够通过字符串插值插入变量 - 类似以下内容:
Console.WriteLine(toBeFormatted);
Run Code Online (Sandbox Code Playgroud)
我试过这样的事情:
var toBeFormatted = $ConfigurationManager.AppSettings["FormattedString"];
Run Code Online (Sandbox Code Playgroud)
或者
Console.WriteLine($toBeFormatted);
Run Code Online (Sandbox Code Playgroud)
但两者都导致错误。有没有办法让编译器知道toBeFormatted应该将字符串用作FormattableString?
好吧,如果没有,我建议使用以下简单的解决方案:
<appSettings>
<add key="FormattedString" value="{0}, {1}." />
</appSettings>
Run Code Online (Sandbox Code Playgroud)
然后在你的代码中:
Console.WriteLine(string.Format(toBeFormatted,greeting, name));
Run Code Online (Sandbox Code Playgroud)