using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using Unity.VisualScripting;
using Unity.VisualScripting.Antlr3.Runtime.Tree;
using UnityEngine;
using UnityEngine.U2D;
using UnityEngine.UI;

public class Main : MonoBehaviour
{
    private Main() { }
    private static Main instance;
    public static Main Instance
    {
        get
        {
            // 인스턴스가 null인 경우 새로 생성
            if (instance == null)
            {
                instance = new Main();
                // 기존의 Start 메서드 내용을 Init 메서드로 옮김
                instance.Init();
            }
            return instance;
        }
    }

    public SpriteAtlas equipmentAtlas;
    [SerializeField] private Image weapon;
    [SerializeField] private Image armor;
    [SerializeField] private Image helmet;
    [SerializeField] private Image shield;
    [SerializeField] private Image accessaries;

    public EquipmentData[] equipmentDatas;
    private int id;

    void Init()
    {
        TextAsset asset = Resources.Load<TextAsset>("data/equipment_data");
        string json = asset.text;
        //Debug.Log(json);

        //현재 문자열을 객체로 역직렬화
        equipmentDatas = JsonConvert.DeserializeObject < EquipmentData[] >(json);

        EquipmentData foundData = this.GetDataById(1002);
        //foreach (EquipmentData equipment in equipmentDatas)
        //{
        //JSON 데이터에서 해당 필드가 비어있거나 값이 없다면, 해당 필드는 역직렬화될 때 0으로 초기화
        //Debug.LogFormat("{0}, {1}, {2}, {3}, {4}", equipment.id, equipment.name, equipment.type, equipment.damage, equipment.defense);
        //}
        Debug.LogFormat("{0}, {1}, {2}, {3}", foundData.id, foundData.name, foundData.type, foundData.defense);

    }

    public EquipmentData GetDataById(int id)
    {
        EquipmentData foundData = null;
        this.id = id;
        for(int i = 0; i < this.equipmentDatas.Length; i++)
        {
            EquipmentData equipmentData = this.equipmentDatas[i];
            if(equipmentData.id == id)
            {
                foundData = equipmentData;
                break;
            }
        }
        return foundData;
    }

    public Sprite GetSpriteImg(string imgName)
    {
        EquipmentData equipmentData = null;
        foreach (var data in equipmentDatas)
        {
            if (data.name == imgName)
            {
                equipmentData = data;
                break;
            }
        }

        if (equipmentData != null)
        {
            string imagePath = "img/" + equipmentData.name;
            Sprite sprite = Resources.Load<Sprite>(imagePath);
            return sprite;
        }
        else
        {
            Debug.LogError("Equipment data with name " + imgName + " not found.");
            return null;
        }
    }

    public void LoadAndSetImage(Image imageComponent, string imgName)
    {
        Sprite sprite = GetSpriteImg(imgName);
        if (sprite != null)
        {
            imageComponent.sprite = sprite;
        }
    }

}

 

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class Weapon : MonoBehaviour
{
    public TMP_Text idText;
    public Image weaponImg;
    private void Start()
    {
        //Sprite weaponSprite = Main.Instance.equipmentAtlas.GetSprite("weaponA");
        //weaponImg.sprite = weaponSprite;

        //Sprite sprite = Resources.Load<Sprite>("img/weaponA");
        //weaponImg.sprite = sprite;

        Main.Instance.LoadAndSetImage(weaponImg, "weaponA");

        //weaponImg = 
        idText.text = Main.Instance.GetDataById(1000).id.ToString();
    }
}

 

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;


public class Shield : MonoBehaviour
{
    public TMP_Text idText;
    public Image shieldImg;

    private void Start()
    {
        Main.Instance.LoadAndSetImage(shieldImg, "shieldA");
        idText.text = Main.Instance.GetDataById(1001).id.ToString();
    }
}

 

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;


public class Armor : MonoBehaviour
{
    public TMP_Text idText;
    public Image armorImg;


    private void Start()
    {
        Main.Instance.LoadAndSetImage(armorImg, "armorA");
        idText.text = Main.Instance.GetDataById(1003).id.ToString();
    }

}

 

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class Accessaries : MonoBehaviour
{
    public TMP_Text idText;
    public Image accessoryImg;

    private void Start()
    {
        Main.Instance.LoadAndSetImage(accessoryImg, "accessoryA");
        idText.text = Main.Instance.GetDataById(1004).id.ToString();
    }
}

 

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class Helmet : MonoBehaviour
{
    public TMP_Text idText;
    public Image helmetImg;
    private void Start()
    {
        Main.Instance.LoadAndSetImage(helmetImg, "helmetA");
        idText.text = Main.Instance.GetDataById(1002).id.ToString();
    }
}

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EquipmentData
{
    public int id;
    public string name;
    public string type;
    public int damage;
    public int defense;
}

상속?

캡슐화 및 다형성과 함께 객체 지향 프로그래밍의

세가지 주요 특성 중 하나

다른 클래스에 정의된 동작을 재사용, 확장 및 수정하는 새 클래스를 만들 수 있다.

 

사용하는 이유?

코드 기능을 재사용, 구현 시간 단축

 

맴버가 상속되는 클래스를 기본 클래스

해당 맴버를 참조하는 클래스를 파생클래스

https://www.youtube.com/watch?v=SiAyDvab-wc&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=37

 

 

단 , 부모가 둘일 수는 없다.

 

새 클래스를 만들 때 기존 클래스의 필드와 메서드를 재사용

 

=> 더 쉽게 만들고 유지 관리할 수 있다

 

 

protected 접근제어자를 사용하는 주된 이유는,

 

해당 클래스나 상속받은 다른 클래스에서만 생성자를 호출할 수 있게 제한함으로써,

의도치 않은 인스턴스 생성을 방지하고 객체의 일관성을 유지하기 위해서

 

 

 

 

상속을 받았다면 부모 클래스의 생성자도 호출됨

 

 

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

namespace Step37
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Marine marineA = new Marine();
            marineA.Init("마린 A", 10);
            marineA.damage = 2;

            Marine marineB = new Marine();
            marineB.Init("마린 B", 10);
            marineB.damage = 2;

            Medic medic = new Medic();
            medic.healValue = 3;

            marineB.Attack(marineA);

            Console.WriteLine("마린 A의 체력 : {0}",marineA.GetHp());
            Console.WriteLine("마린 B의 체력 : {0}",marineB.GetHp());

            medic.Heal(marineA);

            Console.WriteLine("마린 A의 체력 : {0}", marineA.GetHp());
            Console.WriteLine("마린 B의 체력 : {0}", marineB.GetHp());
        }
    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Step37
{
    internal class TerranUnit : StarcraftUnit
    {
        protected int hp;
        protected int maxHp;

        public TerranUnit()
        {
            Console.WriteLine("TerranUnit 클래스 생성자");
        }

        public void Init(string name, int maxHp)
        {
            this.name = name;
            this.maxHp = maxHp;
            this.hp = this.maxHp;
        }

        public void Hit(int damage)
        {
            this.hp -= damage;
            Console.WriteLine("{0}이 피해{1}를 받았습니다", this.name, damage);
        }

        public int GetHp()
        {
            return this.hp;
        }

        public void AddHp(int heal)
        {
            this.hp += heal;

            Console.WriteLine("{0}의 체력이 회복 되었습니다", this.name);

            if(this.hp >= this.maxHp)
            {
                this.hp = this.maxHp;
            }
        }
    }
}

 

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

namespace Step37
{
    internal class StarcraftUnit
    {
        public string name;
        //생성자
        public StarcraftUnit()
        {
            Console.WriteLine("StarcraftUnit 생성자");
        }
    }
}

 

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

namespace Step37
{
    internal class Marine : TerranUnit
    {
        public int damage;
        public Marine()
        {
            Console.WriteLine("Marine 클래스 생성자");

        }

        public void Attack(TerranUnit target)
        {
            target.Hit(this.damage);
        }

    }
}

 

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

namespace Step37
{
    internal class Medic : TerranUnit
    {
        public int healValue;
        public Medic()
        {
            Console.WriteLine("Medic 클래스 생성자");
        }

        public void Heal(TerranUnit target)
        {
            target.AddHp(this.healValue);
        }
    }
}

 

'Study > C#' 카테고리의 다른 글

[C#] 생성자 연결  (0) 2024.06.12
[C#] virtual, override  (0) 2024.06.12
[C#] static 한정자  (0) 2024.06.02
[C#] this 키워드  (0) 2024.05.31
[C#] 점연산자 NullReferenceException  (0) 2024.05.30

메서드 오버로딩?

다형성을 구현하는 방법중 하나

즉, 하나 이상의 형태를 취할 수 있는 능력

https://www.youtube.com/watch?v=UQmok_QRSKY&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=36

 

 

메서드 오버로딩은

동일한 이름을 가진 여러 메서드를 정의하는 것

 

메서드 오버로딩을 사용하는 때

 

1. 매개변수의 수 변경

2. 다른 타입의 매개변수 사용

3. 서로 다른 타입의 매개변수 순서 변경

 

 

 

생성자 오버로딩

 

 

 

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

namespace Step36
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Calculator calc = new Calculator();
            //int result = calc.Add(1, 2);
            //Console.WriteLine(result);

            //result = calc.Add(1, 2, 3);
            //Console.WriteLine(result);

            //calc.Subtract(1.3f, 1.5f);
            //calc.Subtract(5, 1.5f);
            //calc.Subtract(10f, 5);

            //calc.Multiple(1.5f, 2);
            //calc.Multiple(2, 1.5f);
            
            //생성자 오버로딩
            Hero hong = new Hero();
            Hero lim = new Hero("임꺽정");
            Hero jang = new Hero("장길산", 3, 10);
            
        }
    }
}

 

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

namespace Step36
{
    internal class Calculator
    {
        //클래스가 생성되면 기본 생성자를 만들자

        public Calculator()
        {

        }

        //메서드 오버로딩
        public int Add(int a, int b)
        {
            int result = a + b;
            return result;
        }
        //다른 매개변수의 수
        public int Add(int a, int b, int c)
        {
            int result = a + b + c;
            return result;
        }

        public int Subtract(int a, int b)
        {
            int result = a - b;
            return result;
        }
        //다른 타입의 매개변수
        public int Subtract(float a, float b)
        {
            int result = Convert.ToInt32(a - b);
            return result;
        }

        public int Subtract(int a, float b)
        {
            int result = a - (int)b;
            return result;
        }
        //서로다른 매개변수의 순서 변경
        public int Multiple(int a, float b)
        {
            int result = a * (int)b;
            return result;
        }

        public int Multiple(float a, int b)
        {
            int result = (int)a * b;
            return result;
        }
        
        //반환타입이 다른것은 오버로딩 불가능

    }
}

 

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

namespace Step36
{
    internal class Hero
    {
        //생성자
        public Hero()
        {
            Console.WriteLine("매개변수가 없는 기본 생성자");
        }

        //생성자 오버로딩
        public Hero(string anme)
        {
            Console.WriteLine("매개변수가 1개 있는 생성자");

        }

        //생성자 오버로딩
        public Hero(string name, int damage, int maxHp)
        {
            Console.WriteLine("매개변수가 3개 있는 생성자");

        }
    }
}

'낙서장 > C#' 카테고리의 다른 글

virtual ,override, base  (2) 2024.03.08
상속과 다형성  (1) 2024.03.08
흐름 제어  (1) 2024.02.26
데이터를 가공하는 연산자  (0) 2024.02.25
데이터를 담는 변수와 상수  (0) 2024.02.22

특정 개체가 아니라 형식 자체에 속하는

정적 맴버를 정의 할 수 있다.

 

정적 맴버

프로그램이 실행되는 동안 수명이 유지됨

항상 클래스 이름으로 접근됨

 

생성된 인스턴스의 수와 상관 없이

정적 맴버는 항상 한 개

 

정적 메서드는 비정적 필드 및 메서드에 접근 불가

 

https://www.youtube.com/watch?v=CLdJsWLk_wE&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=35

 

 

 

그렇기 때문에 그 동안 Main메서드에서 비정적 메서드를 호출 하거나

맴버에 엑세스 하기 위해 static을 붙여왔다.

 

 

 

정적 생성자는 정적 필드를 초기화 하거나 특정 작업을 한 번만 수행해야 하는데 사용됨

 

 

 

 

정적 생성자는 인스턴스 생성자보다 먼저 호출되며 한번만 실행됨

생성자란?

클래스와 같은 이름을 갖는 함수를 의미

객체가 초기에 생성될 때 자동으로 1회 호출되는 함수

주로 객체 내의 정보를 초기화 하는 수단이며, return 값이 없다

 

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

namespace Step35
{
    internal class CallCenter
    {
        //정적 생성자
        static CallCenter()
        {
            Console.WriteLine("콜센터 정적 생성자");
        }

        //인스턴스 생성자
        public CallCenter()
        {
            Console.WriteLine("콜센터 인스턴스 생성자");
        }
    }
}

 

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

namespace Step35
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var center1 = new CallCenter();
            var center2 = new CallCenter();
        }
    }
}

 

 

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

namespace Step35
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var center1 = new CallCenter(201); //인스턴스 생성시 인수 값(내선번호) 전달
            var center2 = new CallCenter(202);

            Console.WriteLine(CallCenter.number); //정적 맴버는 클래스 이름으로 엑세스

            //정적 메서드 호출
            CallCenter.Call();

            //인스턴스 메서드 호출
            center1.CallExtensionNumber(); //변수에 할당된 CallCenter인스턴스의 맴버 메서드 호출
            center2.CallExtensionNumber();
        }
    }
}

 

 

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

namespace Step35
{
    internal class CallCenter
    {
        //정적 맴버 변수
        public static string number;

        //인스턴스 맴버 변수
        public int extenstionNumber;

        //정적 생성자
        static CallCenter()
        {
            //정적 생성자에서 정적 필드(맴버변수)를 초기화 할 수 있다.
            CallCenter.number = "1588-0000";
            Console.WriteLine("콜센터 정적 생성자");
        }

        //인스턴스 생성자
        public CallCenter(int extenstionNumber) //매개변수로 내선번호 전달
        {
            //this 키워드를 사용해 클래스의 현재 인스턴스의 맴버변수에 접근(맴버 엑세스 연산자 사용, .점 연산자)
            this.extenstionNumber = extenstionNumber;
            Console.WriteLine("콜센터 인스턴스 생성자");
            Console.WriteLine("내선번호 : {0}", this.extenstionNumber); //생성된 인스턴스는 다른 내선번호를 가지게 만듬
        }

        //정적 맴버 메서드
        public static void Call()
        {
            Console.WriteLine("상담 가능한 상담사를 찾고있습니다.");
        }

        //인스턴스 맴버 메서드(내선번호로 전화 걸기)
        public void CallExtensionNumber()
        {
            Console.WriteLine("내선번호({0})로 전화를 겁니다.", this.extenstionNumber);
        }

    }
}

'Study > C#' 카테고리의 다른 글

[C#] virtual, override  (0) 2024.06.12
[C#] 상속  (1) 2024.06.03
[C#] this 키워드  (0) 2024.05.31
[C#] 점연산자 NullReferenceException  (0) 2024.05.30
[C#] 맴버변수와 지역변수  (0) 2024.05.29

 

새게임 시작 시

나머지를 초기화 후 저장

재시작 시

기존에 가지고 가야 할 정보들만 따로 저장하고 시작됨

 

이어하기는 기존의 데이터를 가져옴

 

나머지 도감 클릭시 준비카드 or 행동카드 도감 선택

환경설정 시나와야 할 UI 구성

 

 

this란?

클래스의 현재 인스턴스를 가리키는 키워드

 

https://www.youtube.com/watch?v=w3YquM7W_cY&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=34

 

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

namespace Step34
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Character hong = new Character("홍길동", 3, 10);
            Character lim = new Character("임꺽정", 2, 12);
            Console.WriteLine("캐릭터의 이름: {0}, 공격력: {1}, 체력:{2}/{3} ", hong.name, hong.damage, hong.hp, hong.maxHp);
            Console.WriteLine("캐릭터의 이름: {0}, 공격력: {1}, 체력:{2}/{3} ", lim.name, lim.damage, lim.hp, lim.maxHp);
        }
    }
}

 

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

namespace Step34
{
    internal class Character
    {
        //맴버변수 정의
        public string name;
        public int damage;
        public int hp;
        public int maxHp;

        //생성자
        public Character(string name, int damage, int maxHp)
        {
            this.name = name;
            this.damage = damage;
            this.maxHp = maxHp;
            this.hp = this.maxHp;



        }
    }
}

 

 

 

'Study > C#' 카테고리의 다른 글

[C#] 상속  (1) 2024.06.03
[C#] static 한정자  (0) 2024.06.02
[C#] 점연산자 NullReferenceException  (0) 2024.05.30
[C#] 맴버변수와 지역변수  (0) 2024.05.29
[C#] 생성자 메서드  (0) 2024.05.29

car.name => 맴버 변수

car.Move(); => 맴버 메서드

 

다음과 같이 .을 사용하여 형식 맴버에 액세스

 

참조하고 있지 않는 참조변수에서 맴버에 액세스하려면

NullReferenceException 발생

 

여기서 Exception이란?

애플리케이션 실행 중에 발생하는 오류

 

예시

 

참조가 없는 변수의 맴버를 액세스 하려고 했기 때문에

NullReferenceException 발생

 

'Study > C#' 카테고리의 다른 글

[C#] static 한정자  (0) 2024.06.02
[C#] this 키워드  (0) 2024.05.31
[C#] 맴버변수와 지역변수  (0) 2024.05.29
[C#] 생성자 메서드  (0) 2024.05.29
[C#] 클래스와 new 연산자  (0) 2024.05.29

맴버변수 ?

 

클래스에 정의된 변수

맴버변수는 인스턴스가 메모리에 있는동안 접근 가능

 

지역변수?

메서드에 정의된 변수

메서드가 실행되는 동안 접근 가능

https://www.youtube.com/watch?v=tR376tcsgag&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=32

 

https://www.youtube.com/watch?v=tR376tcsgag&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=32
https://www.youtube.com/watch?v=tR376tcsgag&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=32
https://www.youtube.com/watch?v=tR376tcsgag&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=32
https://www.youtube.com/watch?v=tR376tcsgag&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=32

 

가비지 컬렉션?

메모리를 자동으로 관리해주는 메커니즘

 

https://www.youtube.com/watch?v=tR376tcsgag&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=32
https://www.youtube.com/watch?v=tR376tcsgag&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=32
https://www.youtube.com/watch?v=tR376tcsgag&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=32

 

https://www.youtube.com/watch?v=tR376tcsgag&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=32

 

null은 참조하지 않음

 

https://www.youtube.com/watch?v=tR376tcsgag&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=32
https://www.youtube.com/watch?v=tR376tcsgag&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=32

 

 

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

namespace Step32
{
    internal class Car
    {
        public string name;
        public float speed;
        public Car(string carName)
        {
            name = carName;
            Console.WriteLine("{0}이(가) 자동차가 생성되었습니다", carName);
        }

        public void Move(float moveSpeed)
        {
            speed = moveSpeed;
            Console.WriteLine("{0}속도로 이동합니다", moveSpeed);
        }
    }
}

 

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

namespace Step32
{
    internal class Car
    {
        public string name;
        public float speed;
        public Car(string carName)
        {
            name = carName;
            Console.WriteLine("{0}이(가) 자동차가 생성되었습니다", carName);
        }

        public void Move(float moveSpeed)
        {
            speed = moveSpeed;
            Console.WriteLine("{0}속도로 이동합니다", moveSpeed);
        }
    }
}

 

'Study > C#' 카테고리의 다른 글

[C#] this 키워드  (0) 2024.05.31
[C#] 점연산자 NullReferenceException  (0) 2024.05.30
[C#] 생성자 메서드  (0) 2024.05.29
[C#] 클래스와 new 연산자  (0) 2024.05.29
[C#]메서드 반환타입  (0) 2024.05.28

생성자 메서드?

 

class 내부에 정의된 특수한 메서드

 

생성자?

 

이름이 해당 형식의 이름과 동일한 메서드

 

메서드 이름과 매개 변수 목록만 포함되고

반환 형식은 포함되지 않는다

 

클래스 정의

class Car

{

}

 

생성자 메서드 정의

class Car

{

Car()

{

}

}

https://www.youtube.com/watch?v=S8oQU_FENLw&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=31

 

 

일반 메서드는 정의 후 호출을 통해 실행된다.

 

생성자 메서드는 객체생성시 자동으로 호출된다

 

생성자를 통해 맴버변수의 기본값을 설정할 수 있다

 

 

 

매개변수가 있는 생성자 => 객체 생성시 값을 전달

 

예를들어 자동차 객체를 생성할 때 자동차 이름을 전달

https://www.youtube.com/watch?v=S8oQU_FENLw&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=31

 

https://www.youtube.com/watch?v=S8oQU_FENLw&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=31
https://www.youtube.com/watch?v=S8oQU_FENLw&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=31

 

https://www.youtube.com/watch?v=S8oQU_FENLw&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=31

 

 

 

 

생성자는 클래스안에 정의된 특수한 메서드
반환 타입이 없으며 이름이 클래스명과 동일한 메서드
인스턴스가 생성된 후 자동으로 호출
매개변수가 있는 생성자도 있다.

 

 

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

namespace Step31
{
    internal class Car
    {
        public string name; //맴버 변수

        //생성자 메서드는 클래스의 이름과 동일
        //외부로부터 전달된 인수(문자열값은) 매개변수
        //carName에 할당된다.
        public Car(string carName)
        {
            //생성자에 반환 타입을 작성해서는 안된다.
            Console.WriteLine("생성자가 호출 됨");
            //매개변수 출력
            Console.WriteLine("매개변수 : {0}", carName);
            //맴버변수 출력
            Console.WriteLine("맴버변수 : {0}", name);
            //생성자 메서드 호출이 완료되면
            //매개변수의 값이 사라지므로
            //매개변수의 값을 맴버변수에 할당
            name = carName;
            Console.WriteLine("맴버변수 : {0}", name);
            //이렇게 할당된 맴버 변수는
            //해당 객체의 수명동안 사라지지 않는다
        }
    }
}

 

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

namespace Step31
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //인스턴스가 호출 된후
            //인스턴의 생성자가 호출된다

            //매개 변수가 있는 생성자일 경우 반드시 인수를 전달해야 한다
            //new Car("싼타페");

            //변수에 Car인스턴스 할당
            Car car = new Car("싼타페");
            //car변수의 속성 name 출력
            Console.WriteLine(car.name);
            
        }
    }
}

'Study > C#' 카테고리의 다른 글

[C#] 점연산자 NullReferenceException  (0) 2024.05.30
[C#] 맴버변수와 지역변수  (0) 2024.05.29
[C#] 클래스와 new 연산자  (0) 2024.05.29
[C#]메서드 반환타입  (0) 2024.05.28
[C#] 메서드 매개 변수  (0) 2024.05.28

+ Recent posts