C#

[C#] - 정적 생성자(static constructor) 와 일반 생성자의 차이

Riucc 2019. 4. 12. 11:32

정적 생성자(static constructor) 와 일반 생성자의 차이 

 

- 정적 생성자(static constructor)와 일반 생성자의 차이

     일반적으로 정적 변수들은 많이 사용해보았지만, 정적 생성자를 사용해보지는 않았을 것이다

     정적 생성자는 주로 정적 데이터(static) 초기화, 한 번만 수행해야 하는 특정 작업에 사용한다

     일반 생성자는 new를 통해 인스턴스 객체를 생성할때마다 매번 호출된다

     호출순서 : '정적 필드 초기화 -> 정적 생성자 -> 일반 필드 초기화 -> 일반 생성자' 순이다


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
namespace ConsoleApp1
{
    class Student
    {
        static public int stuCount;
        public Student()
        {
            Console.WriteLine("일반 생성자 호출");
            ++stuCount;
        }
        static Student()
        {
            stuCount = 0;
            Console.WriteLine("정적 생성자 호출 stuCount = 0");
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            Student stu1 = new Student();
            Console.WriteLine($"stuCount = {Student.stuCount}");
            Student stu2 = new Student();
            Console.WriteLine($"stuCount = {Student.stuCount}");
            Student stu3 = new Student();
            Console.WriteLine($"stuCount = {Student.stuCount}");
        }
    }
}
 
cs