c# - 命令初始化静态参数

标签 c# initialization declaration specifications

静态只读参数的初始化顺序有没有规范?

在下面的示例中,是否可以确定创建的数组的长度始终为 6?

public class Foo {
    private static readonly int MAX_STACKSIZE = 6; 
    private static readonly int[] m_stack = new int[MAX_STACKSIZE]; 
}

或者 m_stack 是否有可能在 MAX_STACKSIZE 之前初始化?

@Edit:将const更改为静态只读

最佳答案

编辑:这个答案是在示例代码包含“const”而不是“static readonly”时编写的。它对于问题的当前版本无效 - 我可能会在某个时候写另一个答案来处理这个问题,但我现在没有时间。

无论如何,这都不是有效的 C#,因为您无法将 const int[] 设置为 null 以外的任何值。

但是,在更一般的情况下,C# 规范的第 10.4 节适用:

Constants are permitted to depend on other constants within the same program as long as the dependencies are not of a circular nature. The compiler automatically arranges to evaluate the constant declarations in the appropriate order.

然后给出以下示例:

class A
{
    public const int X = B.Z + 1;
    public const int Y = 10;
}

class B
{
    public const int Z = A.Y + 1;
}

并说...

the compiler first evaluates A.Y, then evaluates B.Z, and finally evaluates A.X, producing the values 10, 11 and 12 in that order.

关于c# - 命令初始化静态参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4781306/

相关文章:

c++ - 在适用性方面,如果 "const int &i"和 "const int i"都是用文字/表达式初始化的,它们有何不同?

c++ - 尝试在声明中仅使用类名构造临时对象

c# - 使用简单 TCP 时如何启用 WCF 压缩?

c# - C# 中枚举值名称的别名

c# - 如何在 WPF 中单击后释放按钮?

c# - 语言表现

initialization - Modelica 中的稳态初始化

c++ - 当两个候选人具有相同的简历资格时,转换函数的初始化是否应该不明确?

c - 如何在 C 中的矩阵(二维数组)内声明 double ?

C++ 构造函数错误