Order of initialization of static parameters

后端 未结 2 1633
渐次进展
渐次进展 2021-01-22 03:00

Few weeks ago, I switched from Java to C#. Today, I had a weird behavior and I try to reproduce it in this simple sample. I\'m using a .net FW 4.

I have three classes: F

相关标签:
2条回答
  • 2021-01-22 03:45

    Normally the compiler warns you if you are trying to use members before they are initialised.

    In this case you circumvent this check as the static member doesn't use the other static member directly, instead it calls the constructor, which uses the other static member.

    The compiler can't protect you from every possible dependency problem, only the simple ones. This is just one step too complex for the compiler to catch.

    It would of course be possible for the compiler to catch something like this, but that would make it more complex for each additional level of dependency, and it's still not possible to catch every situation.

    0 讨论(0)
  • 2021-01-22 04:04

    It is defined as text order - §17.11 in ECMA 334:

    If a class contains any static fields with initializers, those initializers are executed in textual order immediately prior to executing the static constructor.

    As an aside, this gets particularly interesting if you consider partial classes, in which case : it is not defined.

    If in doubt, move the initialization explicitly to a static constructor.


    As for why; consider (note: these are just my own thoughts):

    • "definite assignment" is the thing that usually stops this being an issue, but "definite assignment" does not apply to fields
    • analysing the code in full detail is computationally complex (I'm thinking "halting", perhaps) - so it could only offer an incomplete veneer of safety (which is artificial and could lead to problems in any non-trivial scenario)
    • and due to the partial classes issue, the full order itself is not strictly defined; so it cannot handle the general case - and again, covering a specific case (single class fragment etc) is back to the "thin veneer" (where it only warns for the obvious cases, but can't help with the non-trivial ones)
    0 讨论(0)
提交回复
热议问题