Why doesn't the CLR always call value type constructors

前端 未结 7 845
情深已故
情深已故 2020-12-13 08:52

I have a question concerning type constructors within a Value type. This question was inspired by something that Jeffrey Richter wrote in CLR via C# 3rd ed,

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-13 09:46

    From §18.3.10 of the standard (see also The C# programming language book):

    The execution of a static constructor for a struct is triggered by the first of the following events to occur within an application domain:

    • An instance member of the struct is referenced.
    • A static member of the struct is referenced.
    • An explicitly declared constructor of the struct is called.

    [Note: The creation of default values (§18.3.4) of struct types does not trigger the static constructor. (An example of this is the initial value of elements in an array.) end note]

    So I would agree with you that the last two lines of your program should each trigger the first rule.

    After testing, the consensus seems to be that it consistently triggers for methods, properties, events, and indexers. That means it's correct for all explicit instance members except fields. So if Microsoft's C# 4 rules were chosen for the standard, that would make their implementation go from mostly right to mostly wrong.

提交回复
热议问题