问题描述
beforefieldinit标志有什么作用?
当我查看班级的IL时,我看到了这个标志,但是我不知道这个标志实际上在做什么?
What does beforefieldinit flag do?When I look into the IL of my class I see this flag but I don't know what this flag is actually doing?
推荐答案
有关此问题,请参见。
基本上, beforefieldinit
表示可以在引用任何静态字段之前的任何时候初始化类型。 理论上意味着可以非常懒惰地初始化-如果您调用不涉及任何字段的静态方法,则JIT不需要初始化类型。
Basically, beforefieldinit
means "the type can be initialized at any point before any static fields are referenced." In theory that means it can be very lazily initialized - if you call a static method which doesn't touch any fields, the JIT doesn't need to initialize the type.
在实践中,这意味着该类比其他情况早 进行了初始化-可以这样做在可能使用它们的第一个方法的开始处进行初始化。将其与不应用了 beforefieldinit
的类型进行比较,其中类型初始化必须在第一个 actual 使用。
In practice it means that the class is initialized earlier than it would be otherwise - it's okay for it to be initialized at the start of the first method which might use it. Compare this with types which don't have beforefieldinit
applied to them, where the type initialization has to occur immediately before the first actual use.
因此,假设我们有:
public static void DoSomething(bool which)
{
if (which)
{
FirstType.Foo();
}
else
{
SecondType.Bar();
}
}
如果这两种类型在beforefieldinit中都具有
应用于它们(在C#中,除非类型具有静态构造函数,否则它们在默认情况下会执行此操作),然后在 > DoSomething 方法(通常-不能保证)。如果它们没有 beforefieldinit
,则仅根据标记将其中一个 初始化。
If both types have beforefieldinit
applied to them (which in C# they do by default unless the type has a static constructor) then they'll both be initialized at the start of the DoSomething
method (usually - it's not guaranteed). If they don't have beforefieldinit
then only one of them will be initialized, based on the flag.
这就是为什么当。
这篇关于beforefieldinit标志有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!