静态类中静态字段的初始化顺序
给出以下代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,他们会的,请参阅 C# 规范的第 15.5.6.2 条:
话虽这么说,我认为最好在静态类型初始值设定项(静态构造函数)内进行初始化。
Yes, they will, please see clause 15.5.6.2 of the C# specification:
That being said I think it would be better to do the initialization inside a static type initializer (static constructor).
嗯...我很惊讶它能编译(确实如此,我检查过)。我不知道有任何保证可以保证这一点。使用静态构造函数...
编辑:我接受(参见上面更好的答案)它会起作用;但我对代码的想法是让它尽可能简单明了。如果它不是明显它会起作用(如果你必须问的话它就不可能),那么就不要那样写......
特别是依赖字段的问题顺序:
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:
partial
classesMy advice remains: use a static constructor for this scenario.
乍一看,我不确定,我必须尝试一下,看看它是否可以编译。
鉴于此,我将在静态构造函数中初始化该值。
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.