독개

[C#] 12화 ★레퍼런스의 메모리 구조 및 처리 개념

by #독개#

클래스 선언시 메모리할당

/* 클래스가 객체화된 녀석은 레퍼런스 형이라고 하고
 * int bool 이런 녀석들은 값형이라고 한다
 * 값형과 레퍼런스형은 메모리의 위치와 사용법이 다르기 때문에 다르게 동작한다
 */

class Monster
{
    public int At = 10; //맴버의 변수로써 new monster()시에 Heap에 생긴다
    public int Hp = 100;
    
    public void ATT(Player _player) //_player은 지역변수로써 함수 호출시 Stack에 생긴다
    {
        _player.Hp -= At; //플레이어의 HP는 몬스터의 At로 깍음
    }
}

class Player
{
    public int At = 10;
    public int Hp = 100;
}


namespace _12화_레퍼런스의_메모리_구조_및_처리_개념
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Monster NewMonster은 Stack에 NewMonster이란 포인터로 주소저장
            //new Monster()로써 Heap에 동적할당
            Monster NewMonster = new Monster();
            Player NewPlayer = new Player();

            NewMonster.ATT(NewPlayer);
            
            Console.WriteLine(NewPlayer.Hp); //100에서 -10해서 90으로 변경

        }
    }
}

첫생성

 

 

NewMonster.ATT(NewPlayer);

 

 

블로그의 정보

독한 개발자

#독개#

활동하기