将C#字符串变量转换为可格式化字符串的方法

10
假设在一个C#程序中,我在我的app.config文件中有以下几行代码:
<appSettings>
    <add key="FormattedString" value="{greeting}, {name}." />
</appSettings>

而在我的代码中,我使用它如下:

    private void doStuff()
    {
        var toBeFormatted = ConfigurationManager.AppSettings["FormattedString"];
        string greeting = @"Hi There";
        string name = @"Bob";
    }

我希望使用toBeFormatted变量作为一个FormattableString,以便通过字符串插值来插入变量 - 大致如下:

Console.WriteLine(toBeFormatted);

我尝试了以下方法:

var toBeFormatted = $ConfigurationManager.AppSettings["FormattedString"];

或者

Console.WriteLine($toBeFormatted);

但是这两种方式都会导致错误。有没有一种方法可以让编译器知道toBeFormatted字符串应该用作FormattableString


1
相关:https://dev59.com/BFkS5IYBdhLWcg3wb2Ts - Ehsan Sajjad
1
显然不行。我说“显然”是因为编译器需要在运行时编译替换表达式,虽然这可能是可能的,但它会非常笨拙和低效。此外,请考虑{MySuperDangerousMethodThatFormatsYourHardDriveAndReturnsAnInt()}的恐怖。 - Jeroen Mostert
谢谢,@EhsanSajjad - 很遗憾,这将是一项很酷的补充,但这是有道理的。 - John Bustos
哈哈,@JeroenMostert - 说得好。我想我只是不理解插值字符串的工作原理。现在明白了,谢谢。 - John Bustos
2
值得指出的是,FormattableStringFactory.Create 可以完成编译器的一些工作,但我仍然无法让它评估属性表达式。 - Eric Falsken
1个回答

2

如果不行的话,我建议采用以下简单方法解决:

<appSettings>
   <add key="FormattedString" value="{0}, {1}." />
</appSettings>

然后在您的代码中:

Console.WriteLine(string.Format(toBeFormatted,greeting, name));

1
非常感谢。我知道这个,只是希望仍然有一种方法可以使用字符串插值而不是 String.Format。谢谢!! - John Bustos
2
@JohnBustos 插值是编译时的东西,它需要这些占位符可用,所以我认为您无法通过配置使用它。 - Ehsan Sajjad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接