private const string _DefaultIconPath = _IconsPath + "default.ico";
private const string _IconsPath = "Icons/";
Run Code Online (Sandbox Code Playgroud)
这些字符串在运行时的值:
private readonly string _DefaultIconPath = _IconsPath + "default.ico";
private readonly string _IconsPath = "Icons/";
Run Code Online (Sandbox Code Playgroud)
编译时间错误:
A field initializer cannot reference the non-static field, method, or property '_IconsPath'
Run Code Online (Sandbox Code Playgroud)
private static readonly string _DefaultIconPath = _IconsPath + "default.ico";
private static readonly string _IconsPath = "Icons/";
Run Code Online (Sandbox Code Playgroud)
这些字符串在运行时的值:
null)为什么编译器在示例3中抛出编译错误,类似于示例2?
声明的顺序在static readonly字段定义的情况下很重要,但在const字段定义的情况下则不重要.
编辑:
我理解为什么字符串被初始化为那些特定的值.我不明白的是为什么示例2抛出编译错误,强制初始化发生在构造函数而不是变量声明中(这很有意义),但是示例3的行为方式并不相同.抛出相同的编译错误强制在静态构造函数中进行初始化是不是有意义?
private …Run Code Online (Sandbox Code Playgroud)