简体   繁体   English

在C#中,是否在调用main()方法之前初始化所有静态变量?

[英]In C#, do all static variables get initialized before the main() method is called?

The ones I am particularly concerned about are: 我特别关注的是:

  • static variables in classes that are defined in referenced/dependency classes, contained in external DLLs. 外部DLL中包含的在引用/依赖类中定义的类中的静态变量。 In my example, none of the types in that third party assembly is reference until later in the program. 在我的示例中,该第三方程序集中的任何类型都没有引用,直到该程序的后面。 (let's say 5 min into execution). (假设执行时间为5分钟)。

Will the static variables of that third-party assembly only be loaded then? 这样仅会加载该第三方程序集的静态变量吗?

Thanks, rui 谢谢,瑞

according to C# spec which says: 根据C#规范说:

If a static constructor 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. 否则,将在首次使用该类的静态字段之前,在与实现相关的时间执行静态字段初始化程序。 The example 这个例子

whiteout a static constructor you can not predict exactly when a static variable is initialized but they are guaranteed to be initialized before their first use. 将静态构造函数泛白,您无法准确预测何时初始化静态变量,但是可以保证在首次使用静态变量之前对其进行初始化。 but for sure they are not initialized before you reference their assemblies 但可以肯定的是,在引用它们的程序集之前它们没有被初始化

All static fields are initialized before they are first used. 所有静态字段在首次使用之前均已初始化。 This can be done by a type initializer (static constructor) explicitly declared or implicitly provided by the compiler. 这可以通过编译器显式声明或隐式提供的类型初始化器(静态构造函数)来完成。 Static fields that do not have a value assigned in the class declaration will be initialized to the default value of their corresponding type. 在类声明中未分配值的静态字段将被初始化为其相应类型的默认值。

Be careful if your static fields are object references whose constructors may throw exceptions: 请注意,如果您的静态字段是对象引用,其构造函数可能会引发异常:

class Foo
{
    public Foo() { throw new Exception("boom"); }
}
class Bar
{
    private static Foo baz = new Foo();
    public Bar()
    {
        //trying to create a Bar will throw TypeInitializationException
    }
    public static void BarNone()
    {
        //trying to call a static method on Bar will throw TypeInitializationException
    }
}

You'll get a TypeInitializationException when Bar is first used (either constructed or when a static method on Bar is called), as shown above. 如上所示,在首次使用Bar时(构造方法或调用Bar上的静态方法时),您将获得TypeInitializationException。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM