구조체 형식?

사용자 정의 형식

 

데이터와 관련 기능을 캡슐화할 수 있는 값 형식

 

동작을 거의 제공하지 않거나 작은 데이터 중심 형식을 설계하는데 사용 권장

 

struct 키워드를 사용하여 정의

 

https://www.youtube.com/watch?v=zL5rb-Q5WzE&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=41

 

 

 

 

인스턴스는 new 키워드사용

모든 구조체 형식은 하나 이상의 생성자를 갖는다.

 

 

 

※클래스와 다른점

1. 값형식

2. 상속 불가능

 

매개변수 없는 생성자를 포함 불가

 

맴버 메서드에 virtual, protected 사용 불가

 

유형의 인스턴스가 작고 일반적으로 수명이 짧거나 다른 개체에 포함되는 경우

클래스 대신 구조체를 사용하는 것을 고려

 

다른 모든 경우는 클래스를 사용하자

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

namespace Stet39
{
 
    internal class Program
    {
        static void Main(string[] args)
        {
            //Position pos = new Position(1,1);
            //Position pos = new Position();
            //Position pos;
            //pos.x = 1;
            //pos.y = 1;
            //Console.WriteLine(pos);
            //Position pos = new Position(1,1);
            //pos.SetOrigin();
            //Console.WriteLine("{0}, {1}", pos.x, pos.y);

            Marine marine = new Marine(new Position(1,1));
            Console.WriteLine("마린의 현재 위치 : {0}, {1}", marine.position.x, marine.position.y); ;

            marine.Move(new Position(2, 3));
            Position pos = marine.GetPostion();
            Console.WriteLine("마린의 현재 위치 : {0}, {1}", pos.x, pos.y);

        }
    }
}

 

 

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

namespace Stet39
{
    struct Position
    {
        public int x;
        public int y;

        public Position(int x, int y)//매개 변수 없는 생성자 사용불가
        {
            this.x = x;
            this.y = y;
        }

        public void SetOrigin()
        {
            this.x = 0;
            this.y = 0;
        }
    }
}

 

 

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

namespace Stet39
{
    internal class Marine
    {
        public Position position;
        public Marine(Position position)
        {
            this.position = position;
        }
        public void Move(Position targetPosition)
        {
            Console.WriteLine("{0}, {1}로 이동합니다", targetPosition.x, targetPosition.y);
            this.position = targetPosition;
        }

        public Position GetPostion()
        {
            return this.position;
        }
    }
}

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

[C#] 업캐스팅, 다운캐스팅  (0) 2024.06.13
[C#] 생성자 연결  (0) 2024.06.12
[C#] virtual, override  (0) 2024.06.12
[C#] 상속  (1) 2024.06.03
[C#] static 한정자  (0) 2024.06.02

업캐스팅?

인스턴스의 타입을 파생(자식) 클래스 타입에서

기본 클래스 타입으로 변환

 

다운 캐스팅?

인스턴스의 타입을 기본 클래스 타입에서

파생 클래스 타입으로 변환

 

업캐스팅은 암시적

https://www.youtube.com/watch?v=yVDljROH1Jg&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=40
https://www.youtube.com/watch?v=yVDljROH1Jg&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=40

 

다운캐스팅은 명시적

 

 

 

 

 

접근 가능한 맴버는 참조변수의 타입에 의해 결정됨

 

 

 

변환할 수 없는 경우 as 연산자가 null을 반환

캐스트 식과 달리 as 연산자는 예외를 throw하지 않는다.

 

as 연산자 변환 성공한 경우

 

as 연산자 변환 실패한 경우

 

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

namespace Step38
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Marine marine = new Marine();
            //marine.Attack();
            //marine.StimPack();

            //업캐스팅(암시적)
            //TerranUnit unit = new Marine();
            //unit.Attack();
            //unit.StimPack(); //호출 불가

            //업캐스팅 (명시적)
            //TerranUnit unit = (TerranUnit)new TerranUnit();
            //unit.Attack();
            //unit.StimPack(); //호출불가

            //TerranUnit unit =  new Marine(); //암시적 업캐스팅
            //Marine marine = (Marine)unit; //다운 캐스팅은 명시적이어야함
            //marine변수의 값은 Marine의 인스턴스
            //marine.Attack();
            //marine.StimPack(); //호출 가능

            /*주의 사항*/
            //부모 클래스 인스턴스 생성 후
            //자식 클래스 타입으로 (다운캐스팅) 할수 없다.
            //Marine marine = (Marine)new TerranUnit();
            //marine.Attack();
            //marine.StimPack(); //호출가능

            //is 연산자를 사용해서
            //형식 변환이 가능한지 테스트 가능

            //TerranUnit unit = new TerranUnit();
            //bool canDownCast = unit is Marine;
            //Console.WriteLine(canDownCast); //False

            //Marine marine = new Marine();
            //bool canUpCast = marine is TerranUnit;
            //Console.WriteLine(canUpCast); // True
            //TerranUnit unit = marine; //암시적 업캐스팅

            
            //TerranUnit unit = new Marine(); //암시적 업캐스팅
            //bool canUpCast = unit is TerranUnit;
            //Console.WriteLine(canUpCast); //True
            //Marine marine = (Marine)unit; //명시적 다운캐스팅

            //as 연산자를 사용해 명시적으로 캐스팅 하기
            //Marine marine = new Marine();
            //TerranUnit unit = marine as TerranUnit;
            //Console.WriteLine(unit); //Step38.Marine => 성공

            TerranUnit unit = new TerranUnit();
            Marine marine = unit as Marine;
            Console.WriteLine("marine : {0}", marine); //marine : => 변환이 실패하면 결과값은 null
            //즉, 예외를 발생시키지 않는다.

        }
    }
}

 

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

namespace Step38
{
    internal class TerranUnit
    {
        public void Attack()
        {
            Console.WriteLine("공격합니다.");
        }
        //public TerranUnit() { }
    }
}

 

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

namespace Step38
{
    internal class Marine : TerranUnit
    {
        public void StimPack()
        {
            Console.WriteLine("스팀팩을 활성화합니다.");
        }
    }
}

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

[C#] 구조체  (0) 2024.06.14
[C#] 생성자 연결  (0) 2024.06.12
[C#] virtual, override  (0) 2024.06.12
[C#] 상속  (1) 2024.06.03
[C#] static 한정자  (0) 2024.06.02

생성자 연결은 생성자가 동일하거나

기본 클래스의 다른 생성자를 호출하는 접근 방식

즉, 생성자에서 다른 생성자 호출

 

여러 생성자를 정의하는 클래스가 있을 때 사용

 

 

가장 많은 매개변수로 구성된 하나의 생성자에만 값을 할당

그리고 다른 두 생성자가 호출될 때 해당 생성자 호출

 

상속에서 기본 생성자 연결

 

상속에서 매개변수 있는 생성자 연결

 

즉 , 생성자 연결을 통해 매개변수 수가 가장 많은 생성자가 호출된다

 

 

생성자 연결 과정

 

 

상속 생성자 연결 과정

 

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

namespace Step37_3
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //new Marine();
            new Marine("홍길동");
            //new Marine("홍길동", 8);
        }
    }
}

 

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

namespace Step37_3
{
    internal class TerranUnit
    {
        protected string name;
        protected int damage;
        public TerranUnit()
        {
            Console.WriteLine("TerranUnit의 생성자");
        }

        public TerranUnit(string name) : this(name, 0)
        {
            this.name = name;
            Console.WriteLine("매개변수가 1개있는 생성자");
        }

        public TerranUnit(string name, int damage)
        {
            this.name = name;
            this.damage = damage;
            Console.Write("매개 변수가 2개 있는 TerranUnit 생성자");
        }
    }
}

 

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

namespace Step37_3
{
    internal class Marine : TerranUnit
    {
        public Marine() : base() //없으면 암시적으로 동작
        {
            Console.WriteLine("Marine 생성자");
        }

        public Marine(string name) : base(name) //매개변수 이름을 동일하게
        {
            Console.WriteLine("매개변수 1개 있는 Marine 생성자, name : {0} : ", this.name);
        }
        
        public Marine(string name, int damage) : base(name, damage)
        {
            Console.WriteLine("매개변수 2개 있는 Marine 생성자, name : {0}, damage : {1}", this.name, this.damage);
        }
    }
}

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

[C#] 구조체  (0) 2024.06.14
[C#] 업캐스팅, 다운캐스팅  (0) 2024.06.13
[C#] virtual, override  (0) 2024.06.12
[C#] 상속  (1) 2024.06.03
[C#] static 한정자  (0) 2024.06.02

virtual 키워드는

기본 클래스에서 정의된 메서드를

파생 클래스에서 재정의하도록 허용

 

static, abstract, private 한정자와 함께 사용 불가

 

override 한정자?

상속된 메서드의 구현을 확장하거나 수정

 

https://www.youtube.com/watch?v=kmsocjH-keQ&list=PLTFRwWXfOIYBmr3fK17E0VhKPyYrGy75z&index=39

 

base 키워드?

파생 클래스 내에서 기본 클래스의 맴버에 엑세스하는데 사용

 

부모클래스에서 virtual
파생 클래스에서 override

자식 클래스에서 부모클래스 맴버 엑세스 base

 

 

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

namespace Step37_2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Marine marine = new Marine();
            marine.name = "마린1";

            Firebat firebat = new Firebat();
            firebat.name = "파이어뱃1";

            marine.Attack();
            firebat.Attack();
        }
    }
}

 

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

namespace Step37_2
{
    class TerranUnit
    {
        public string name;
        //생성자
        public TerranUnit()
        {
            Console.WriteLine("TerranUnit 클래스의 생성자");
        }
        
        public virtual void Attack()
        {
            Console.WriteLine("{0}이(가) 공격 합니다", this.name);
        }
        protected void Reload(string weaponName) //자식만 접근 가능
        {
            Console.WriteLine("{0}이(가) {1}을 장전을 합니다", this.name, weaponName); ;
        }
    }
}

 

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

namespace Step37_2
{
    internal class Marine : TerranUnit
    {
        //생성자
        public Marine()
        {
            Console.WriteLine("Marine클래스의 생성자");
        }
        public override void Attack()
        {
            base.Reload("총");
            Console.WriteLine("{0}이(가) 총으로 공격합니다.", this.name);
        }
    }
}

 

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

namespace Step37_2
{
    internal class Firebat : TerranUnit
    {
        public Firebat()
        {
            Console.WriteLine("Firebat클래스의 생성자");
        }

        public override void Attack()
        {
            base.Reload("화염방사기");
            Console.WriteLine("{0}이(가) 화염방사기로 공격합니다.", this.name);
        }
        
        
    }
}

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

[C#] 업캐스팅, 다운캐스팅  (0) 2024.06.13
[C#] 생성자 연결  (0) 2024.06.12
[C#] 상속  (1) 2024.06.03
[C#] static 한정자  (0) 2024.06.02
[C#] this 키워드  (0) 2024.05.31

상속?

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

세가지 주요 특성 중 하나

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

 

사용하는 이유?

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

 

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

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

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=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

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