Yang.공부방

Boxing 및 Unboxing

C#/과제2019. 3. 29. 16:57

Boxing

: 값 형식(Stack) -> Object형식(Heap)으로 변환하는 프로세스

: Heap에 저장한다

: 암시적이다

int i =123;
object o =i;

Unboxing

: Object -> 값 형식으로 변환

: 개체에서 값 형식이 추출됩니다.

: 명시적이다

o = 123;
i = (int)o; //o의 주소값

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

[Collection]ArrayList  (0) 2019.04.01
//미완// Collection[컬렉션]  (0) 2019.03.31
(3.25) 몬스터 공격하기 ver.수정  (0) 2019.03.26
Stack 과 Heap  (0) 2019.03.25
몬스터 처치하기  (0) 2019.03.25

Array Class (배열클래스)

배열생성 및 조작, 검색, 정렬하여 모든배열의 기본클래스 역할을 수행하도록 메서드를 제공


Array [배열] 

: 동일한 유형의 여러 변수를 배열 데이터구조에 저장가능

: 기본값은 참조타입 : null, 숫자타입 : 0 이다

: 배열의 형식은 추상기본유형 Array에서 파생참조형식이다. (IEnumerable 및 lEbumerable <T> 를 구현하므로 foreach반복문을 사용할수있다)


상속 : Object -> Array


[1차원 배열 예시 int형] 

1
2
int[] arrayName = new int[5];
//int[] arrayName(배열클래스 인스턴스를 담는다) = int형 배열클래스의 인스턴스를 생성 (기본값 : 0)
cs
(int 형이므로 기본값은 0으로 초기화)


[1차원 배열 예시 string형] 

1
2
string[] arrayName5 = new string[5];
//string형 배열클래스 인스턴스를 생성 (기본값 : null)
cs


[1차원 배열 또다른 사용법] 

1
2
int[] arrayName = { 12345 };
// ** 배열클래스의 인스턴스를 arrayName3 에 담는다.
cs
(이렇게 코딩해도 위와 동일하게 작성이 된다.)


[1차원 배열 초기화] 

1
2
int[] arrayName2 = new int[5] { 12345 };
// 출력 값 : 1,2,3,4,5 (여기서 배열의 인덱스는 0,1,2,3,4 이다.
cs
(인덱스는 0으로 시작한다.)


[배열특성의 메소드]

(이미지 참조 : https://m.blog.naver.com/sonicheroes1/220947806856)

<T> 가 붙은 메소드는 형식매개변수(Type Parameter)라고 부르며, 호출 시 T의 위치에 배열기반자료형을 매개변수로 입력하면 컴파일러가 알아서 처리해준다.


[foreach 예시]

1
2
3
4
5
int[] sortEx = { 1,2,3,4,5,6,7,8,9,10 };
foreach(int foreachEx in sortEx)
{
Console.WriteLine(foreachEx);
} //출력값 1 2 3 4 5 6 7 8 9 10
cs

인자로 들어온 ArrayEx 내부의 인덱스 끝까지 순환해주는 반복문, 배열에서 많이 사용

사용법 : foreach(자료형 element in 배열명)

참조 : https://blockdmask.tistory.com/313


[Sort 예시]

1
2
3
4
5
6
7
            int[] sortEx = new int[5] { 541021 };
            Array.Sort(sortEx);
 
            for(int i=0; i<5; i++)
            {
                Console.WriteLine(sortEx[i]);
            }//출력값 : 1 2 4 5 10

cs
(작은 수 -> 큰 수로 정렬이 되어 출력이 된다)

참조 : https://mongyang.tistory.com/86

[BinarySearch<T> 예시]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] ArrayEx = { 12,23,34,45,56,67,78,89,91,10 };
            string[] ArrayEx2 = { "가""나""다""라""마" };
 
            Console.WriteLine(Array.BinarySearch<int>(ArrayEx, 89));
            Console.WriteLine(Array.BinarySearch<string>(ArrayEx2, "라"));
        }
    }
}결과 값 : 7 , 3

cs

정렬된 Array에서 값을 검색

참조 : https://docs.microsoft.com/ko-kr/dotnet/api/system.array.binarysearch?view=netframework-4.7.2










1차원배열 doc : https://docs.microsoft.com/ko-kr/dotnet/csharp/programming-guide/arrays/single-dimensional-arrays

Array Method 종류 : https://m.blog.naver.com/sonicheroes1/220947806856

GetValue Method doc : https://docs.microsoft.com/ko-kr/dotnet/api/system.reflection.propertyinfo.getvalue?view=netframework-4.7.2

string.IndexOf Method doc : https://docs.microsoft.com/ko-kr/dotnet/api/system.string.indexof?view=netframework-4.7.2



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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace GameEnums
{
    class GameEnum
    {
        public enum eCamp //진영
        {
            None,
            Alliance,
            Hord
        }
 
        public enum eTribe //(얼라이언스)부족
        {
            None,//0 
            Human,//1
            Dwarf,//2
            Nightelf,//3
            Gnomes,//4
            Draenei,//5
            Werewolf//6
        }
 
        public enum eTribe2 //(호드)부족2
        {
            None,//0
            Oak,//1
            Undead,//2
            Tauren,//3
            Troll,//4
            Bloodelves,//5
            Goblin//6
        }
 
        public enum job
        {
            DeathKnight, //죽음의기사
            Thief,//도적
            Hunter,//사냥꾼
            Monk,//수도사
            Wizard,//마법사
            Warlock,//흑마법사
            Priests,//사제
            Paladin,//성기사
            Warrior,//전사
 
            Powwow,//주술사
 
        }
    }
}
 
cs

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace GameEnums
{
    class Character
    { public string name;
        private float x;
        private float y;
 
        public Character()
        {
        }
 
        public Character(string name)
        {
            this.name = name;
        }
 
        public void Move(float x, float y)
        {
 
            Console.WriteLine($"{name}님이 (x : {x} , y : {y}) 위치로 이동하였습니다.");
        }
    }
}
 
cs


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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
 
namespace GameEnums
{
    class App
    {
        public string AllianceList = "1.인간 2.드워프 3.나이트엘프 4.노움 5.드레나이 6.늑대인간";
        public string HordList = "1.오크 2.언데드 3.타우렌 4.트롤 5.블러드엘프 6.고블린";
 
        public App()
        {
            Console.WriteLine("진영을 선택해 주세요");
            while (true)
            {
                string input = Console.ReadLine();
                if (input == "얼라이언스")
                {
                    Console.WriteLine("얼라이언스를 선택하셨습니다");
                    //Thread.Sleep(500);
                    Console.WriteLine("종족을 선택해주세요");
                    Console.WriteLine(AllianceList);
 
                    //foreach (var Values in Enum.GetValues(typeof(GameEnums.eTribe))){}
                    int intinput = Convert.ToInt16(Console.ReadLine());
                    if (intinput == 1)
                    {
                        Console.WriteLine($"고르신 종족은 {GameEnum.eTribe.Human}입니다.");
                        Console.WriteLine("직업을 선택해주세요");
 
                    }
                    else if (intinput == 2)
                    {
                        Console.WriteLine($"고르신 종족은 {GameEnum.eTribe.Dwarf}입니다.");
                    }
                    else if (intinput == 3)
                    {
                        Console.WriteLine($"고르신 종족은 {GameEnum.eTribe.Nightelf}입니다.");
                    }
                    else if (intinput == 4)
                    {
                        Console.WriteLine($"고르신 종족은 {GameEnum.eTribe.Gnomes}입니다.");
                    }
                    else if (intinput == 5)
                    {
                        Console.WriteLine($"고르신 종족은 {GameEnum.eTribe.Draenei}입니다.");
                    }
                    else if (intinput == 6)
                    {
                        Console.WriteLine($"고르신 종족은 {GameEnum.eTribe.Werewolf}입니다.");
                    }
                    else if (intinput == 0)
                    {
                        break;
                    }
 
                }
                else if (input == "호드")
                {
                    Console.WriteLine("호드를 선택하셨습니다");
                    //Thread.Sleep(500);
                    Console.WriteLine("종족을 선택해주세요");
                    int intinput = Convert.ToInt16(Console.ReadLine());
                    if (intinput == 1)
                    {
                        Console.WriteLine($"고르신 종족은 {GameEnum.eTribe2.Oak}입니다.");
                    }
                    else if (intinput == 2)
                    {
                        Console.WriteLine($"고르신 종족은 {GameEnum.eTribe2.Undead}입니다.");
                    }
                    else if (intinput == 3)
                    {
                        Console.WriteLine($"고르신 종족은 {GameEnum.eTribe2.Tauren}입니다.");
                    }
                    else if (intinput == 4)
                    {
                        Console.WriteLine($"고르신 종족은 {GameEnum.eTribe2.Troll}입니다.");
                    }
                    else if (intinput == 5)
                    {
                        Console.WriteLine($"고르신 종족은 {GameEnum.eTribe2.Bloodelves}입니다.");
                    }
                    else if (intinput == 6)
                    {
                        Console.WriteLine($"고르신 종족은 {GameEnum.eTribe2.Goblin}입니다.");
                    }
                    else if (intinput == 0)
                    {
                        break;
                    }
                }
                else if (input != "얼라이언스" || input == "호드")
                {
                    Console.WriteLine("잘못 입력하셨습니다");
                    Thread.Sleep(1000);
                    Console.WriteLine("프로그램을 종료합니다");
                    break;
                }
 
            }
            /*
            Console.WriteLine("캐릭터의 이름을 선택하여 주세요");
            var character = new Character(Console.ReadLine());
            Console.WriteLine("캐릭터의 이름은 {0}입니다", character.name);
            character.Move(3f , 5f);
            */
        }
    }
}
cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace GameEnums
{
    class Program
    {
        static void Main(string[] args)
        {
            new App();
        }
    }
}
 
cs


Class : 사용자정의 데이터타입, 참조형식이다.

struct는 값형식(복사시 값들이 복사 된다), class는 참조형식(복사시 참조만 복사 된다.) 


조형식의 변수 선언시 new연산자를 사용하여 클래스의 인스턴스를 명시적으로 만들 수 있다.

접근지정자 : public(어디서든지 접근 가능)

private(동일 클래스안에서만 접근 가능)

protected(동일 클래스의 코드, 파생클래스의 코드에서만 접근가능)

internal(동일한 어셈블리의 코드에서는 형식이나 멤버에 액세스할 수 있지만 다른 어셈블리의 코드에서는 액세스할 수 없습니다.) <-???

protected internal(동일한 어셈블리의 코드 또는 다른 어셈블리의 파생 클래스에서 형식이나 멤버에 액세스할 수 있습니다.)<-????

인스턴스 : 프로그램 실행 시 메모리에 할당하는 변수 또는 함수 (객체,개체라고도 한다) , 인스턴스가 객체보다 큰 범위를 포함

객체와 인스턴스 차이 : 객체(Object)는 구현할 대상, 클래스(Class)는 객체를 구현하기 위한 설계도, 인스턴스(Instance)는 설계도에 따라 구현된 실체



class 참조 : https://docs.microsoft.com/ko-kr/dotnet/csharp/programming-guide/classes-and-structs/classes

class 참조 : http://charlie0301.blogspot.com/2016/04/c-class.html

접근지정자 참조 : http://blog.naver.com/PostView.nhn?blogId=skyarro&logNo=120095630095

인스턴스 생성자 참조 : https://docs.microsoft.com/ko-kr/dotnet/csharp/programming-guide/classes-and-structs/instance-constructors

인스턴스 참조 : http://jungwoo5394.blogspot.com/2015/08/instance.html

객체와 인스턴스 차이 참조 : https://cerulean85.tistory.com/149     또는   https://alfredjava.wordpress.com/2008/07/08/class-vs-object-vs-instance/



new : 개체를 만들고 생성자를 호출

개체를 만들 때 사용 작성 법 : new키워드 뒤에 클래스 이름과 ();를 넣는다.( 개체생성 및 생성자 호출)

생성자 : class , struct를 만들 때 마다 해당 생성자를 호출


new 참조 : https://docs.microsoft.com/ko-kr/dotnet/csharp/language-reference/keywords/new-operator


dot(.)연산자 : 구조체버에 액세스에 사용(접근 할 수 있게 해준다.)

네임스페이스 또는 형식의 멤버에 액세스할 수 있다.

namespace : 파일들을 관리하기 위한 폴더?  함수 이름이 똑같을 시에 충돌을 방지하기 위한 name



namespace 참조 : https://docs.microsoft.com/ko-kr/dotnet/csharp/programming-guide/namespaces/#namespaces-overview

namespace 참조 : https://leehosung3576.tistory.com/20

namespace 참조 : https://baseofmint.tistory.com/1

dot연산자 참조 : https://docs.microsoft.com/ko-kr/dotnet/csharp/language-reference/operators/member-access-operator



형식변환


암시적 변환 : 형식이 안전하고 데이터가 손실되지 않으므로 특수 구문이 필요없다. (파생클래스 -> 기본클래스로 변환)

작은범위 -> 큰범위 변환 ex) int 형 -> short형 변환, float형 -> int형 변환, 숫자형 -> char형 변환



명시적 변환(캐스트변환) : 캐스트연산자 필요 (int),(double) 과 같이 괄호안에 변환 할 타입을 밝힌다.



사용자 정의 변환



도우미클래스를 사용한 변환



명시적변환 참조2 : http://soen.kr/book/dotnet/book/3-4-2.htm


멤버변수 : 클래스 안에 정의되어있는 변수 , 어떤 메소드에도 포함되어 있지 않는 변수

특징 : 클래스 내부 어디서든 사용가능, 값이 사라지지 않는다.



지역변수메소드 안에 선언된 변수(로컬변수라고도 불린다)

특징 : 선언된 메소드 안에서만 사용이 가능, 한번 실행이 되면 초기화



클래스 객체 생성 및 출력 코드 노트에 적고 읽기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ClassEx
{
    
    class EX1
    {
        public string name = "양재준";
        public EX1()
        {
            this.name = null;
        }
    }
}
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ClassEx
{
    
    class EX1
    {
        public string name = "양재준";
        public EX1()
        {
            this.name = null;
        }
    }
}
cs


null 키워드 : 참조형식 변수의 기본값

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
70
71
72
73
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace study_01
{
    class Test
    {
        public Test()
        {
            string monsterName = "오우거";
            int monsterHp = 123;
            int monsterMaxhp = 123;
 
            string heroName = "홍길동";
            int heroHp = 80;
            int heroAttackdamage = 4;
 
            Console.WriteLine("몬스터의 이름 : {0}입니다", monsterName);
            Console.WriteLine("몬스터의 체력은 : {0}/{1} 입니다", monsterHp, monsterMaxhp);
            Console.WriteLine("몬스터는 사납고 무섭습니다. \n");
 
            Console.WriteLine($"용사의 이름 : {heroName}입니다");
            Console.WriteLine($"용사의 체력 : {heroHp}입니다");
            Console.WriteLine($"용사의 공격력 : {heroAttackdamage}입니다 \n");
 
            Console.WriteLine("용사가 몬스터를 공격했습니다.");
            Console.WriteLine($"몬스터는 {heroAttackdamage}데미지를 받았습니다.");
            Console.WriteLine("몬스터의 체력은 {0}/{1}입니다 \n", monsterHp - heroAttackdamage, monsterMaxhp);
 
            Console.WriteLine("공격을 더 하시겠습니까? ( Y / N ) \n");
 
            while (true)
            {
                ConsoleKeyInfo inputkey = Console.ReadKey();
                if (inputkey.Key == ConsoleKey.Y)
                {
                    Console.Clear();
                    Thread.Sleep(1000);
                    Console.Clear();
                    monsterHp -= heroAttackdamage ;
                    Console.BackgroundColor = ConsoleColor.DarkRed;
                    Console.WriteLine("\n 몬스터는 {0}의 피해를 받았습니다.", heroAttackdamage);
                    Console.ResetColor();
 
                    if (monsterHp <= 0)
                    {
                        Console.WriteLine("\n몬스터를 처치하였습니다.");
 
                        break;
                    }
                    Console.WriteLine("몬스터의 체력은 {0}", monsterHp);
                    continue;
                }
                else if (inputkey.Key == ConsoleKey.N)
                {
                    Console.Clear();
                    Console.WriteLine("\n용사가 도망쳤습니다. \n");
                    break;
                }
                else if (inputkey.Key != ConsoleKey.Y && inputkey.Key != ConsoleKey.N)
                {
                    Console.Clear();
                    Console.WriteLine("\n잘못 누르셨습니다.");
                }
 
            }
        }
    }
}
cs


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

//미완// Collection[컬렉션]  (0) 2019.03.31
Boxing 및 Unboxing  (0) 2019.03.29
Stack 과 Heap  (0) 2019.03.25
몬스터 처치하기  (0) 2019.03.25
(3.22)값 형식  (0) 2019.03.25