小编Dyl*_*dor的帖子

初始化优先级 - const vs readonly vs static readonly

例1

private const string _DefaultIconPath = _IconsPath + "default.ico";
private const string _IconsPath = "Icons/";
Run Code Online (Sandbox Code Playgroud)

这些字符串在运行时的值:

  • _DefaultIconPath:"Icons/default.ico"
  • _IconsPath:"图标/"

例2

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)

例3

private static readonly string _DefaultIconPath = _IconsPath + "default.ico";
private static readonly string _IconsPath = "Icons/";
Run Code Online (Sandbox Code Playgroud)

这些字符串在运行时的值:

  • _DefaultIconPath:"default.ico"(_IconsPath评估为null)
  • _IconsPath:"图标/"

为什么编译器在示例3中抛出编译错误,类似于示例2?

声明的顺序在static readonly字段定义的情况下很重要,但在const字段定义的情况下则不重要.

编辑:

我理解为什么字符串被初始化为那些特定的值.我不明白的是为什么示例2抛出编译错误,强制初始化发生在构造函数而不是变量声明中(这很有意义),但是示例3的行为方式并不相同.抛出相同的编译错误强制在静态构造函数中进行初始化是不是有意义?


另一个例子

private …
Run Code Online (Sandbox Code Playgroud)

.net c#

6
推荐指数
1
解决办法
988
查看次数

标签 统计

.net ×1

c# ×1