gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 19:41:47 26 4
gpt4 key购买 nike

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

在下面的示例中,是否可以确定创建的数组的长度始终为 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com