什么时候在 C# 中初始化静态变量? [英] When do static variables get initialized in C#?

查看:24
本文介绍了什么时候在 C# 中初始化静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道静态变量(在类中)什么时候出现(初始化)?是在第一次调用实例构造函数之后还是在类加载之后?类加载何时发生?

I was wondering about when does a static variable(in a class) come into picture(initialized)? Is it after the instance constructor called for the first time or after the class loads? When does a class loading occur?

推荐答案

哦,那很复杂.这取决于是否设置了 beforefieldinit 标志,而后者(在 C# 中)取决于是否存在静态构造函数.更糟的是;在 .NET 4 中我相信行为发生了变化,使其比以前更懒惰".

Oh, that is complex. It depends on whether the beforefieldinit flag is set, which in turn (in C#) depends on whether there is a static constructor. And worse; in .NET 4 I believe the behaviour changed to make it more "lazy" than it used to be.

坦率地说,我不会在这里编写任何特定行为;简单地说:静态字段将在您尝试使用它们之前进行初始化,只要您使用常规代码来访问它们即可.

Frankly, I wouldn't code to any specific behaviour here; simply: static fields will be initialized before you try to use them, as long as you use regular code to access them.

Jon Skeet 在这里这里

Jon Skeet has a good write-up on this here and here

这篇关于什么时候在 C# 中初始化静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆