How does a static constructor work?

前端 未结 10 1331
迷失自我
迷失自我 2020-12-04 06:03
namespace MyNameSpace
{
    static class MyClass
    {
        static MyClass()
        {
            //Authentication process.. User needs to enter password
                


        
10条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 06:53

    It's ensured that a static class's constructor has been called before any of its methods get executed. Example:

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Press enter");
            Console.ReadLine();
            Boop.SayHi();
            Boop.SayHi();
            Console.ReadLine();
        }
    
    }
    
    static class Boop
    {
        static Boop()
        {
            Console.WriteLine("Hi incoming ...");
        }
    
        public static void SayHi()
        {
            Console.WriteLine("Hi there!");
        }
    }
    

    Output:

    Press enter

    // after pressing enter

    Hi incoming ...

    Hi there!

    Hi there!

提交回复
热议问题