Order of initialization of static parameters

后端 未结 2 1639
渐次进展
渐次进展 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.

提交回复
热议问题