Why does interpolating a const string result in a compiler error?

后端 未结 4 1088
忘了有多久
忘了有多久 2020-12-09 15:01

Why does string interpolation in c# does not work with const strings? For example:

private const string WEB_API_ROOT = \"/private/WebApi/\";
private const st         


        
4条回答
  •  臣服心动
    2020-12-09 15:18

    Interpolated strings are simply converted to calls to string.Format. So your above line actually reads

    private const string WEB_API_PROJECT = string.Format("{0}project.json", WEB_API_ROOT);
    

    And this is not compile time constant as a method call is included.


    On the other hand, string concatenation (of simple, constant string literals) can be done by the compiler, so this will work:

    private const string WEB_API_ROOT = "/private/WebApi/";
    private const string WEB_API_PROJECT = WEB_API_ROOT + "project.json";
    

    or switch from const to static readonly:

    private static readonly string WEB_API_PROJECT = $"{WEB_API_ROOT}project.json";
    

    so the string is initialized (and string.Format called) at the first access to any member of the declaring type.

提交回复
热议问题