Order of static constructors/initializers in C#

后端 未结 4 1431
梦如初夏
梦如初夏 2020-12-03 10:02

While working on a C# app I just noticed that in several places static initializers have dependencies on each other like this:

static private List         


        
4条回答
  •  情深已故
    2020-12-03 10:56

    Yes, you were lucky. C# appears to execute the code in the order it appears in the class.

    static private List a = new List() { 0 };
    static private List b = new List() { a[0] };
    

    Will work but ...

    static private List b = new List() { a[0] };
    static private List a = new List() { 0 };
    

    Will fail.

    I would recommend putting all your dependencies in one place, the static constructor is the place for this.

    static MyClass()
    {
      a = new List() { 0 };
      b = new List() { a[0] };
    }
    

提交回复
热议问题