静态类中静态字段的初始化顺序

发布于 2024-08-06 08:03:52 字数 270 浏览 4 评论 0原文

给出以下代码:

public static class Helpers
{
   private static Char[] myChars = new Char[] {'a', 'b'};

   private static Int32 myCharsSize = myChars.Length;
}

是否保证在我使用 myChars 的长度分配给 myCharsSize 之前初始化 myChars

given the following code:

public static class Helpers
{
   private static Char[] myChars = new Char[] {'a', 'b'};

   private static Int32 myCharsSize = myChars.Length;
}

Is it guaranteed that myChars will be initialized before I use its length to assign to myCharsSize?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

北凤男飞 2024-08-13 08:03:53

是的,他们会的,请参阅 C# 规范的第 15.5.6.2 条

类的静态字段变量初始值设定项对应于
按文本顺序执行的赋值序列
它们出现在类声明中(§15.5.6.1)。在一个
部分类,“文本顺序”的含义由以下指定
§15.5.6.1。如果类中存在静态构造函数(第 15.12 节),
静态字段初始值设定项的执行立即发生在
执行该静态构造函数。否则,静态字段
初始化程序在依赖于实现的时间之前执行
第一次使用该类的静态字段。

话虽这么说,我认为最好在静态类型初始值设定项(静态构造函数)内进行初始化。

Yes, they will, please see clause 15.5.6.2 of the C# specification:

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 (§15.5.6.1). Within a
partial class, the meaning of "textual order" is specified by
§15.5.6.1. If a static constructor (§15.12) 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.

That being said I think it would be better to do the initialization inside a static type initializer (static constructor).

千纸鹤带着心事 2024-08-13 08:03:53

嗯...我很惊讶它能编译(确实如此,我检查过)。我不知道有任何保证可以保证这一点。使用静态构造函数...


编辑:我接受(参见上面更好的答案)它会起作用;但我对代码的想法是让它尽可能简单明了。如果它不是明显它会起作用(如果你必须问的话它就不可能),那么就不要那样写......

特别是依赖字段的问题顺序:

  • 如果您移动代码(我经常这样做),
  • 它可能会破坏如果您将代码拆分为 partial 类,它可能会破坏

我的建议仍然是:在这种情况下使用静态构造函数。

Hmm... I'm surprised that compiles (it does, I checked). I'm not aware of any guarantee that would make this safe. Use a static constructor...


Edit: I accept (see better answer above) that it will work; but my idea with code is to keep it as simple and obvious as possible. If it isn't obvious that it will work (and it can't be if you have to ask), then don't write it that way...

In particular, problems with relying on field order:

  • it can break if you move code around (which I often do)
  • it can break if you split the code into partial classes

My advice remains: use a static constructor for this scenario.

芸娘子的小脾气 2024-08-13 08:03:53

乍一看,我不确定,我必须尝试一下,看看它是否可以编译。

鉴于此,我将在静态构造函数中初始化该值。

At first glance, I wouldn't be sure, and I had to try this out to see if it even compiled.

Given that, I would initialize the value in a static constructor.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文