in C# does Static constructor run for each initialization of object, or only once?

后端 未结 2 672
一整个雨季
一整个雨季 2021-02-04 22:16

in my Class I have a static dictionary of strings object which contains a big number of Items (it reads from a file and initial them) I wrote a static constructor to do so and i

2条回答
  •  盖世英雄少女心
    2021-02-04 22:24

    It runs once for the type, per AppDomain. Not once per instance. From the C# 4 spec, section 10.12:

    The static constructor for a closed class type executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

    • An instance of the class type is created.
    • Any of the static members of the class type are referenced.

    Note the part about it being per closed class. So if you have a generic type Foo, then Foo is a separate type to Foo (etc), will have separate static fields, and will have its static constructor invoked separately.

    提交回复
    热议问题