简体   繁体   中英

Class Initialize() in C#?

In Obj-c there is the static Initialize method which is called the first time that class is used, be it statically or by an instance. Anything like that in C#?

You can write a static constructor with the same syntax as a normal constructor, except with the static modifier (and no access modifiers):

public class Foo {
    static Foo() {
        // Code here
    }
}

Usually you don't need to do this, however - static constructors are there for initialization, which is normally fine to do just in static field initializers:

public class Foo {
    private static readonly SomeType SomeField = ...;
}

If you're using a static constructor to do more than initialize static fields, that's usually a design smell - but not always.

Note that the presence of a static constructor subtly affects the timing of type initialization , requiring it to be executed just prior to the first use - either when the first static member access, or before the first instance is created, whichever happens first.

There is a static constructor. As per msdn :

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

public class Foo { static Foo() {} //static constructor }

Yes, it is called a constructor .

By MSDN:

public class Taxi
{
    public bool isInitialized;

    //This is the normal constructor, which is invoked upon creation.
    public Taxi()
    {
        //All the code in here will be called whenever a new class
        //is created.
        isInitialized = true;
    }

   //This is the static constructor, which is invoked before initializing any Taxi class
   static Taxi()
   {
       Console.WriteLine("Invoked static constructor");
   } 
}

class TestTaxi
{
    static void Main()
    {
        Taxi t = new Taxi(); //Create a new Taxi, therefore call the normal constructor
        Console.WriteLine(t.isInitialized); 
    }
}

//Output:
//Invoked static constructor
//true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM