Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Static Constructor ใน C# คืออะไร

Static Constructor เป็น Constructor ที่ประกาศด้วยคีย์เวิร์ด static เป็นบล็อกโค้ดแรกที่ทำงานในคลาส และทำงานเพียงครั้งเดียวตลอดวงจรชีวิตของคลาส

ตัวอย่าง

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Difference
{
    class Demo
    {
        static int val1;
        int val2;

        static Demo()
        {
            Console.WriteLine("This is Static Constructor");
            val1 = 70;
        }

        public Demo(int val3)
        {
            Console.WriteLine("This is Instance Constructor");
            val2 = val3;
        }

        private void show()
        {
            Console.WriteLine("First Value = " + val1);
            Console.WriteLine("Second Value = " + val2);
        }

        static void Main(string[] args)
        {
            Demo d1 = new Demo(110);
            Demo d2 = new Demo(200);
            d1.show();
            d2.show();
            Console.ReadKey();
        }
    }
}

Static Constructor จะทำงานก่อน Instance Constructor และทำงานเพียงครั้งเดียวเมื่อโหลดคลาสครั้งแรก