gan*_*o55 2 c# string string-interpolation
我正在使用这样的代码:
public static class Program {
public static void Main() {
Console.WriteLine(hello);
}
internal static readonly string hello = $"hola {name} {num}";
internal static readonly string name = $"Juan {num}";
public const int num = 4;
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,当我获得 hello 的值时,它返回给我“hola 4”,因此在插入另一个使用插值的字符串时似乎存在问题。我的预期行为是“hola Juan 4 4”,或者如果语言不支持这种链式插值,则编译时会出错。
有人知道为什么 C# 会出现这种行为吗?
静态字段按照它们声明的顺序进行初始化。那么会发生什么:
hello和name都是null。num是一个常量。hello被初始化。name还在null。但是,num是一个常量,因此可以正确替换。hello有价值"hola 4"name 被初始化。 为什么numconst的事实会有所不同?请记住,编译器在编译时将 const 的值直接替换到它使用的地方。因此,如果您查看编译器生成的内容,您会看到:
public static class Program
{
internal static readonly string hello = string.Format("hola {0} {1}", name, 4);
internal static readonly string name = string.Format("Juan {0}", 4);
public const int num = 4;
public static void Main()
{
Console.WriteLine(hello);
}
}
Run Code Online (Sandbox Code Playgroud)
注意 const 的值是如何编译到它使用的地方的。
当您有相互依赖的静态字段时,您要么需要非常小心地声明它们的顺序,要么使用静态构造函数通常更安全(且更具可读性!):
public static class Program {
static Program() {
name = $"Juan {num}";
hello = $"hola {name} {num}";
}
public static void Main() {
Console.WriteLine(hello);
}
internal static readonly string hello;
internal static readonly string name;
public const int num = 4;
}
Run Code Online (Sandbox Code Playgroud)