我正在使用这样的代码:

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;
}

在这种情况下,当我获得hello的值时,它会返回给我“hola 4”,因此在插值另一个使用插值的字符串时似乎出现了问题。
我的预期行为是“hola Juan 4 4”,或者如果该语言不支持这种链式插值,则会在编译时出错。

有人知道C#为什么会得到这种行为吗?

最佳答案

静态字段按照声明的顺序初始化。所以发生的是:

  • 最初,helloname都是nullnum是一个常量。
  • hello已初始化。 name仍然是null。但是,num是const,因此可以正确替换。 hello的值为"hola 4"
  • name已初始化。


  • 为什么num是const的事实为何有所作为?请记住,编译器在编译时将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);
        }
    }
    

    (由SharpLab提供)

    请注意,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;
    }
    

    关于c# - 静态字符串的链式插值无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59784765/

    10-16 19:14