본문 바로가기
c# 입문

[c#] CSharp this 키워드, static키워드

by javaman 2022. 7. 9.

this 키워드

다른 생성자 호출!

using System;

namespace Class
{
    //클래스와 구조체 차이점
    class Program
    {
      class Knight
        {
            //필드
            static int id = 100;
            int hp;
            int attack;

            Knight()
            {
                hp = 100;
                attack = 10;

            }
            Knight(int hp):this()// 또 다른 생성자 호출
            {
                this.hp = hp;
            }
            Knight(int hp, int attack) : this(hp)//또 다른 생성자 호출
            {
                this.hp = hp;
                this.attack = attack;

            }
        }
        static void Main(string[] args)
        {
          
        }
    }
}

 

static 키워드

:

인스턴스가 함께 공유, 오로지 한개만 존재!

클래스에 종속적인 변수 , 클래스 이름 자체로 호출 가능!

 

using System;

namespace Class
{
    //클래스와 구조체 차이점
    class Program
    {
      class Knight
        {
            //필드
            static int id = 100;
            int memberId;
            int hp;
            int attack;

            static void hello()
            {
                //static메서드에서는 
                //static이 아닌 필드 변수에 접근할 수 없음
                //static메서드는 인스턴스 변수가 할당 되기 전에 할당되기 때문

                Console.WriteLine();

                // WriteLine(): static 메서드 
                //클래스 이름 자체로 호출 가능

            }
            Knight()
            {
                
                    
                hp = 100;
                attack = 10;

              //static변수의 이용
                id++;
                this.memberId = id;//인스턴스를 생성할 때마다 1씩 증가
                



            }
            
        }
        static void Main(string[] args)
        {
          
        }
    }
}