静态只读属性不返回指定的值

Static Readonly Properties not Returning Values Specified

我有一个 class,其中包含大量静态只读变量,这些变量将在我运行后存储在配置文件中。其中,我有一个默认字体大小值,以及相当多的引用此默认字体大小的其他变量。这些变量中只有一个是 returning 0 而不是默认字体大小值。

我的 FontName 变量也有类似的问题,但为简洁起见,将它们排除在示例代码之外。

相关代码如下,按照它在我的 class 中出现的顺序排列。我尝试将默认字体大小声明移动到正文字体大小声明的正上方;这导致所有变量为 return 0 而不是默认字体大小。将声明返回到其原始位置导致其他变量再次开始工作。

我还尝试将变量更改为静态 属性,只有 getter。这 属性 return 是预期的默认字体大小。

我仔细检查了下面列出的所有声明是否存在于同一范围内。

当然,我做了一个完整的解决方案清理和重建,行为没有改变。

另请注意,变量不会抛出异常:它们只是 returning 0。

//private static float _BodyFontSize { get => _DefaultFontSize; }  //returns 9
private static readonly float _BodyFontSize = _DefaultFontSize;    //returns 0

...

private void MyMethod()
{
   //where my breakpoint is at

   ...
}

...

private static readonly float _DefaultFontSize = 9;
...
private static readonly float _DetailsFontSize = _DefaultFontSize;   //returns 9
...
private static readonly float _AddressFontSize = _DefaultFontSize;   //returns 9

...

private void AnotherMethod()
{
   ...
}

...

private static readonly float _BlurbFontSize = _DefaultFontSize;  //returns 9

语言规范 static field initialization section 解释了此行为:

The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (Static constructors) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.

所以在你的情况下 _BodyFontSize_DefaultFontSize 之前初始化并使用 float 的默认值 0。在 _DefaultFontSize 之后移动 _BodyFontSize 将修复你的问题(就像工作问题一样),但我认为更好的选择是在 static constructor 中处理这个初始化,尽管它们是简单的分配。