Yang.공부방

속성

C#/과제2019. 4. 3. 01:44

읽기전용(get 포함 , set 미포함)[속성이란]

: 전용필드의 값을 읽기(get),쓰기(set),계산하는 유연한 메커니즘을 제공하는 멤버

접근자라는 특수 메서드이다.

메서드의 안정성, 유연성 수준을 올리는데 도움을 준다.


[개요]

클래스구현, 검증코드를 숨기는 동시에 값을 가져오고 설정방법을 공개적으로 노출할 수 있다.


get속성 접근자 : 속성값반환하는데 사용 (읽기전용(get 포함 , set 미포함))

: private필드의 값을 반환

set속성 접근자 : 새 값을 할당하는데 사용 (쓰기전용(set포함, get미포함))

:private필드의 값을 할당 전 데이터 유효성 검사

value키워드 : set접근자가 할당하는 값을 정의




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

Dictionary<TKey,TValue>Class  (0) 2019.04.03
[Collection]ArrayList  (0) 2019.04.01
//미완// Collection[컬렉션]  (0) 2019.03.31
Boxing 및 Unboxing  (0) 2019.03.29
(3.25) 몬스터 공격하기 ver.수정  (0) 2019.03.26

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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_07
{
    public class Inventory<T> where T : Item, new()
    {
        private List<T> items;
 
        public Inventory()
        {
            this.items = new List<T>();
        }
 
        public void AddItem(T item, out bool result)
        {
            if (item == null)
            {
                result = false;
                return;
            }
            else
            {
                Item foundItem = null;
                foreach (var element in this.items)
                {
                    if (element.name.Equals(item.name))
                    {
                        foundItem = element;
                    }
                }
 
                if (foundItem != null)
                {
                    foundItem.stack += item.stack;
                    result = true;
                }
                else
                {
                    result = true;
                    this.items.Add(item);
                }
            }
        }
 
        public T GetItem(string name, int stack = 1
        {
            Item foundItem = null;
            Item rtnItem = null;
 
            foreach (var item in this.items)
            {
                if (item.name == name)
                {
                    foundItem = item;
                }
            }
 
            if (foundItem != null)
            {
                var getStack = 0;
                var remainStack = foundItem.stack;
 
                if (stack >= foundItem.stack)
                {
                    getStack = foundItem.stack;
                    remainStack = 0;
                }
                else {
                    getStack = stack;
                    remainStack = foundItem.stack - getStack;
                    foundItem.stack -= getStack;
                }
 
                rtnItem = new T();
                rtnItem.name = foundItem.name;
                rtnItem.stack = getStack;
 
                if (remainStack <= 0)
                {
                    this.RemoveItem(foundItem.name);
                }
            }
 
            return rtnItem as T;
        }
 
        public bool RemoveItem(string name)
        {
            foreach (var element in items)
            {
                if (element.name.Equals(name))
                {
                    this.items.Remove(element);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            return false;
        }
 
        public T FindItem(string name)
        {
            foreach (var element in this.items)
            {
                if (element.name == name)
                {
                    return element as T;
                }
            }
            return default (T);
        }
 
        public void UpdateItem(ref T item, string name, int stack)
        {
            if (item == null) {
                Console.WriteLine("업데이트 실패");
                return;
            }
            
            item.name = name;
            item.stack = stack;
        }
 
        public void DisplayItems()
        {
            if (items.Count <= 0)
            {
                Console.WriteLine("인벤토리에 아이템이 없습니다.");
            }
            else
            {
                foreach (var item in this.items)
                {
                    Console.WriteLine("-> {0} x{1}", item.name, item.stack);
                }
            }
        }
    }
}
cs



[Collection]ArrayList

C#/과제2019. 4. 1. 01:29

[ArrayList]  : 사용하지 않는것을 권장함 

배열과 유사한 collection(배열 : 고정된개수, ArrayList : 동적)

  • 상속 : Object -> ArrayList

  • List와 흡사하지만 ArrayList는 Object Type으로 구성(모든type변수를 담을 수 있다)되어 있으며 

       데이터활용 시 Boxing과Unboxing이 불가피하므로 형식의 불안정성 증가 및 속도저하가 List보다 훨씬 크다.

  • 필요에 따라 동적으로 증가

  • 인덱스로 컬렉션 요소에 접근이 가능하고 특정요소를 바로 읽고 쓰기가능




[ArrayList 함수] 변수를 가지고있다.

Add() :개체를 Array 끝부분에 추가합니다 (값은 null이 될 수 있다)

1
2
3
4
5
6
7
8
9
10
11
12
ArrayList arrFruits = new ArrayList();
var idx = arrFruits.Add("사과");
Console.WriteLine("idx ; {0}", idx);
arrFruits.Add("오렌지");
arrFruits.Add("포도");
Console.WriteLine(arrFruits); //출력값 : arrFruits의 인스턴스
//Add메서드 , 반환타입 : int , 매개변수 Object
 
foreach(Object list in arrFruits)
{
    Console.WriteLine(list);
}
cs

AddRange() 끝 부분에 ICollector의 요소를 복사

Insert() : 지정된 인덱스에 요소 삽입

Remove() : 맨 처음 발견된 요소 삭제

RemoveAt() : 지정된 인덱스에서 요소 삭제

BinarySearch() : 이진 검색하여 특정요소 찾기 (검색 전 Sorting)

Reverse() : 순서를 반대로 전환

Sort() : 정렬

Contain() : 요소가 ArrayList에 있는지 확인

Clear() : 모든요소 삭제



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

Dictionary<TKey,TValue>Class  (0) 2019.04.03
속성  (0) 2019.04.03
//미완// Collection[컬렉션]  (0) 2019.03.31
Boxing 및 Unboxing  (0) 2019.03.29
(3.25) 몬스터 공격하기 ver.수정  (0) 2019.03.26

Collection이란? (자료구조 모음)

개체 그룹을 만들고 관리한다

[개체를 그룹화 하는 방법 2가지]

1. 개체배열생성

2. 개체컬렉션생성

작업하는 개체그룹이 동적으로 확장, 축소

일부 컬렉션의 경우 모든개체의 키를 할당하여 개체를 빠르게 검색 가능

클래스이므로 요소 추가 시 인스턴스를 선언해야 한다.

단일 데이터 형식의 요소만 포함된 경우,네임스페이스사용을 선언해야 한다 (Ex. Using System.Collections; , 구체적형식의 개체가 아닌 Object형식을 개체요소로 저장)

다른 데이터형식을 추가할 수 없도록 형식안전성을 적용


[Generic]제너릭컬렉션

검색할 경우 형식을 결정하거나 변환할 필요 없다

모든 항목에 동일한 데이터 형식이 있는 경우 유용하다.

원하는 데이터 형식만 추가할 수 있도록 한다.



List<T> 

필요에 따라 크기가 동적으로 증가하는 개체배열 (Boxing, Unboxing)

검색,정렬,수정 메서드 제공


[일반화?]

: 클래스 또는 메서드를 선언하고 인스턴스화 할 때 까지 하나 이상의 형식사양을 따르는 클래스 및 메서드를 디자인할 수 있도록 만드는 형식

<T>

형식을 컴파일러에서 자동으로 유추한다(제약조건,반환 값 만으로는 형식매개변수유추 불가)



Boxing, Unboxing 참조 : https://yangjae.tistory.com/manage/newpost/14?type=post&returnURL=https://yangjae.tistory.com/14

Boxing, Unboxing 참조 doc : https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing




IndexOf(object) 

: 인스턴스 멤버 메서드 (검색할때 해당문자열이 없을 시 인덱스 -1표시)

1
2
3
4
5
6
7
8
9
10
11
12
static void Main(string[] args)
{
ArrayList arrFruits = new ArrayList();
var idx = arrFruits.Add("사과");
arrFruits.Add("오렌지");
arrFruits.Add("포도");
 
idx = arrFruits.IndexOf("포도");
Console.WriteLine(idx); // 출력값 :2
idx = arrFruits.IndexOf("포또");
Console.WriteLine(idx); // -1 으로 표시
}
cs

[Hashtable]

[Queue]

[Stack]






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

속성  (0) 2019.04.03
[Collection]ArrayList  (0) 2019.04.01
Boxing 및 Unboxing  (0) 2019.03.29
(3.25) 몬스터 공격하기 ver.수정  (0) 2019.03.26
Stack 과 Heap  (0) 2019.03.25

 


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


namespace Inventory
{
    class Item
    {
        public string name;
        //public string type;
        public int count;
        public int itemMincount;
        public int itemMaxcount;
        
        

        public Item(string name, int count = 0, int itemMincount=0 , int maxcount = 10)
        {
            this.name = name;
            this.count = count;
            this.itemMincount = itemMincount;
            this.itemMaxcount = maxcount;
        }


    }
}

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

namespace Inventory
{
    class Function
    {
        List<Item> items = new List<Item>();

        public Function() //아이템 기본 목록
        {
            items.Add(new Item("초보자용 몽둥이"));
            items.Add(new Item("초보자용 방패"));
            items.Add(new Item("체력포션"));
            items.Add(new Item("마나포션"));
        }

        public void inventory()
        {
            while (true)
            {
                Console.WriteLine("\t\t\t[인벤토리]\n");
                Console.WriteLine("1.아이템추가  2.아이템버리기  3.아이템목록  4.새로운아이템");
                string input = Console.ReadLine();
                Console.Clear();
                if (input == "아이템추가" || input == "1" || input == "추가")
                {
                    Add();
                }
                else if (input == "아이템삭제" || input == "2" || input == "삭제")
                {
                    Delete();
                }
                else if (input == "아이템목록" || input == "3" || input == "검색")
                {
                    itemlist();
                }
                else if (input == "새로운아이템" || input == "4" || input == "목록")
                {
                    newitem();
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("잘못입력하셨습니다.");
                    Console.ResetColor();
                }
            }
        }

        public void Add()//아이템 추가
        {
            while (true)
            {
                Console.WriteLine("어떤 아이템을 추가하시겠습니까? \n");
                Console.WriteLine("1.검  2.방패  3.체력포션  4.마나포션  0.뒤로가기");
                string input = Console.ReadLine();
                Console.Clear();
                if (input == "검" || input == "1")
                {
                    if (items[0].count >= items[0].itemMaxcount)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("검을 더이상 습득할 수 없습니다. \n");
                        Console.ResetColor();
                    }
                    else
                    {
                        items[0].count++;
                        Console.WriteLine("검이 추가되었습니다");
                    }
                }
                else if (input == "방패" || input == "2")
                {
                    if (items[1].count >= items[1].itemMaxcount)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("방패를 더이상 습득할 수 없습니다. \n");
                        Console.ResetColor();
                    }
                    else
                    {
                        items[1].count++;
                        Console.WriteLine("방패가 추가되었습니다");
                    }
                }
                else if (input == "체력포션" || input == "3")
                {
                    if (items[2].count >= items[2].itemMaxcount)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("체력포션을 더이상 습득할 수 없습니다. \n");
                        Console.ResetColor();
                    }
                    else
                    {
                        items[2].count++;
                        Console.WriteLine("체력포션이 추가되었습니다");
                    }
                }
                else if (input == "마나포션" || input == "4")
                {
                    if (items[3].count >= items[3].itemMaxcount)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("마나포션을 더이상 습득할 수 없습니다. \n");
                        Console.ResetColor();
                    }
                    else
                    {
                        items[3].count++;
                        Console.WriteLine("마나포션이 추가되었습니다");
                    }
                }

                else if (input == "뒤로가기" || input == "0")
                {
                    inventory();
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("잘못입력하셨습니다.");
                    Console.ResetColor();
                }
            }
        }

        public void newitem()
        {
            Console.WriteLine("추가하실 아이템을 입력하여주세요.");
            if (items.Count > 10)
            {
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.WriteLine("더이상 추가하실 수 없습니다. [{0}/10]", items.Count);
                Console.ResetColor();
            }
            else if (items.Count < 10)
            {
                items.Add(new Item(Console.ReadLine()));
                int i = 4;
                Console.WriteLine("{0}을 추가하셨습니다", items[i].name);
                i++;
            }
        }

        public void itemlist()
        {
            
            for (int i = 0; i < items.Count; i++)
            {
                if (items[i].count == 0)
                {
                    Console.WriteLine("아이템이 없습니다.");
                }
                else if (items[i] != null)
                {
                    Console.WriteLine("이름 : {0}\t [{1}/10] ", items[i].name, items[i].count);
                }
            }
        }

        public void Delete()
        {
            while (true)
            {
                Console.WriteLine("버리실 아이템을 선택해주세요 \n");
                Console.WriteLine("1.검  2.방패  3.체력포션  4.마나포션  0.뒤로가기");
                string input = Console.ReadLine();
                Console.Clear();
                if (input == "검" || input == "1")
                {
                    if (items[0].count <= items[0].itemMincount)
                    {
                        items[0].count--;
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("아이템이 더이상 없습니다");
                        Console.ResetColor();
                    }
                }
                else if (input == "방패" || input == "2")
                {
                    if (items[0].count <= items[0].itemMincount)
                    {
                        items[0].count--;
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("아이템이 더이상 없습니다");
                        Console.ResetColor();
                    }
                }
                else if (input == "체력포션" || input == "3")
                {
                    if (items[0].count <= items[0].itemMincount)
                    {
                        items[0].count--;
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("아이템이 더이상 없습니다");
                        Console.ResetColor();
                    }
                }
                else if (input == "마나포션" || input == "4")
                {
                    if (items[0].count <= items[0].itemMincount)
                    {
                        items[0].count--;
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("아이템이 더이상 없습니다");
                        Console.ResetColor();
                    }
                }

                else if (input == "뒤로가기" || input == "0")
                {
                    inventory();
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("잘못입력하셨습니다.");
                    Console.ResetColor();
                }
            }
        }
    }
}

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

namespace Inventory
{
    class Program
    {
        static void Main(string[] args)
        {
            var Funtion = new Function();
            Funtion.inventory();
            Console.ReadKey();
        }
    }
}

 

 

아이템 추가 시 중복 제거 및 인벤토리공간 추가 기능 미완성