为什么插入const字符串会导致编译器错误? [英] Why does interpolating a const string result in a compiler error?
问题描述
为什么C#中的字符串插值不适用于const字符串?例如:
Why does string interpolation in c# does not work with const strings? For example:
private const string WEB_API_ROOT = "/private/WebApi/";
private const string WEB_API_PROJECT = $"{WEB_API_ROOT}project.json";
从我的角度来看,所有内容在编译时都是已知的。还是要在以后添加的功能?
From my point of view, everything is known at compile time. Or is that a feature that will be added later?
编译器消息:
分配给'DynamicWebApiBuilder.WEB_API_PROJECT'的表达式必须是常量。
The expression being assigned to 'DynamicWebApiBuilder.WEB_API_PROJECT' must be constant.
非常感谢!
推荐答案
插值的字符串仅转换为对 string.Format
的调用。因此,您上面的行实际上是读取
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.
另一方面,字符串 concatenation (具有简单,恒定的字符串常量)可以由编译器完成,因此会起作用:
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";
或从 const
切换到静态只读
:
private static readonly string WEB_API_PROJECT = $"{WEB_API_ROOT}project.json";
因此将初始化字符串(和 string.Format
被调用)在对声明类型的任何成员的首次访问中。
so the string is initialized (and string.Format
called) at the first access to any member of the declaring type.
这篇关于为什么插入const字符串会导致编译器错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!