포스트

(C#) 19. Static의 정체

static

Static

  • 최초 작성일: 2021년 3월 21일(월)

##

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System;

namespace Static
{
    class Program
    {
        class Knight
        {
            // 필드
            static public int counter = 1;    // 오로지 1개만 존재!

            public int id;
            public int hp;
            public int attack;

            // static 함수 -> 클래스에 종속적 (유일성)
            static public void Test()
            {
                counter++;
            }

            static public Knight CreateKnight()
            {
                Knight knight = new Knight();
                knight.hp = 100;
                knight.attack = 1;
                return knight;
            }
            public Knight()
            {
                id = counter;
                counter++;

                hp = 100;
                attack = 10;
                Console.WriteLine("생성자 호출!");
            }
            public Knight Clone()
            {
                Knight knight = new Knight();
                knight.hp = hp;
                knight.attack = attack;
                return knight;
            }

            public void Move()
            {
                Console.WriteLine("Knight Move");
            }

            public void Attack()
            {
                Console.WriteLine("Knight Attack");
            }
        }

        static void Main(string[] args)
        {
            Knight knight = Knight.CreateKnight();  // static
            knight.Move();  // 일반

            Console.WriteLine();
            
            Random rand = new Random();
            rand.Next(0, 2);  //static이 아님.
        }
    }
}

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.