变量中的字符串插值

String Interpolation in variable

我有一个 class,它只包含字符串常量。称它为 Class A. 我在这里声明以下变量。

public static string SetScore = $"Score[@Set='{currentSet}']";

还有一个 class,我们称之为 Class B。我将在 class B 中使用我的 SetScore 变量。现在这个 class B知道什么是 currentSet.

问题是Class A不知道什么是'currentSet'。

除了在 class B 中声明 SetScore 或使用 String.Format 之外,是否有任何解决方案?

不能那样插值。 Jiter 只是不知道上下文或何时使用该变量的任何线索。

想通了,什么时候换掉。第一次使用?如果你想在不同的上下文中替换多个 Representations 怎么办,它应该考虑哪个范围。听起来很难预测

不过,如果这是一种安慰。你可以这样做

public static string SetScore = "Score[@Set='{0}']";
...
result = string.Format(SetScore,currentSet)

Interpolated Strings (C# Reference)

Used to construct strings. An interpolated string looks like a template string that contains interpolated expressions. An interpolated string returns a string that replaces the interpolated expressions that it contains with their string representations.

更多

You can use an interpolated string anywhere you can use a string literal. The interpolated string is evaluated each time the code with the interpolated string executes. This allows you to separate the definition and evaluation of an interpolated string.