'C#'에 해당되는 글 80건

  1. 2019.10.31 10.31 제너릭을 이용해 사용자 지정 타입 활용하기 (where문 비활용)
  2. 2019.10.31 10.31 제너릭을 이용해 사용자 지정 타입 활용하기 (where문 활용)
  3. 2019.10.31 ref 와 out
  4. 2019.10.31 초기화
  5. 2019.10.31 박싱과 언박싱
  6. 2019.10.30 10.30 클래스로 LinkedList 구현하기 (메서드, 속성의 재귀호출)
  7. 2019.10.24 10.23 Stack 활용하기
  8. 2019.10.24 10.23 배열에서 숫자이동시키기

10.31 제너릭을 이용해 사용자 지정 타입 활용하기 (where문 비활용)

C#/실습 2019. 10. 31. 14:10

예제:

코드:

 

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 _10._31_step1
{
    
    class App
    {
        public App()
        {
            Inventory<Item> inventory = new Inventory<Item>(10);
            inventory.AddItem(new Item(10"장검"));
            inventory.AddItem(new Item(11"단검"));
            inventory.AddItem(new Item(12"활"));
            Console.WriteLine("초기 배열 값:");
            inventory.Print();
            inventory.RemoveItem("단검");
            Console.WriteLine("단검 지운 값:");
            inventory.Print();
            Console.WriteLine("활 찾기");
            Console.WriteLine(inventory.FindItem("활").Id);
 
            
        }
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _10._31_step1
{
    class Inventory <T> //where T: Item //Item 클래스나 Item 파생 클래스만 들어올 수 있다.
    {
        private T[] items;
        public T this[int i]
        {
            get
            {
                return this.items[i];
            }
        }
        public void AddItem(T item)
        {
            for (int i=0; i<items.Length; i++)
            {
                if(items[i] == null)
                {
                    items[i] = item;
                    break;
                }
            }
        }
        public void RemoveItem(string name)
        {
            for(int i =0; i<items.Length; i++)
            {
                if(items[i] is Item)
                {
                    if((items[i] as Item).Name == name)
                    {
                        items[i] = default;
                    }
                }                
            }
        }
        public T FindItem(string name)
        {
            for (int i = 0; i < items.Length; i++)
            {
                if (items[i] is Item)
                {
                    if ((items[i] as Item).Name == name)
                    {
                        return items[i];
                    }
                    continue;
                }
                continue;
            }
            return default;
        }
        public void Print()
        {
            foreach(var data in items)
            {
                if(data != null && data is Item)
                {
                    Item item = data as Item;
                    Console.WriteLine("ID: {0}  Name: {1}"item.Id, item.Name);
                }
            }
        }
 
        public Inventory(int capacity)
        {
            this.items = new T[capacity];
        }
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _10._31_step1
{
    class Item
    {
        public int Id { get; private set; }
        public string Name { get; private set; }
        public Item(int id, string name)
        {
            this.Id = id;
            this.Name = name;
        }
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

:

10.31 제너릭을 이용해 사용자 지정 타입 활용하기 (where문 활용)

C#/실습 2019. 10. 31. 13:51

예제:

코드:

 

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 _10._31_step1
{
    
    class App
    {
        public App()
        {
            Inventory<Item> inventory = new Inventory<Item>(10);
            inventory.AddItem(new Item(10"장검"));
            inventory.AddItem(new Item(11"단검"));
            inventory.AddItem(new Item(12"활"));
            Console.WriteLine("초기 배열 값:");
            inventory.Print();
            inventory.RemoveItem("단검");
            Console.WriteLine("단검 지운 값:");
            inventory.Print();
            Console.WriteLine("활 찾기");
            Console.WriteLine(inventory.FindItem("활").Id);
 
            
        }
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _10._31_step1
{
    class Inventory <T> where T: Item //Item 클래스나 Item 파생 클래스만 들어올 수 있다.
    {
        private T[] items;
        public T this[int i]
        {
            get
            {
                return this.items[i];
            }
        }
        public void AddItem(T item)
        {
            for (int i=0; i<items.Length; i++)
            {
                if(items[i] == null)
                {
                    items[i] = item;
                    break;
                }
            }
        }
        public void RemoveItem(string name)
        {
            for(int i =0; i<items.Length; i++)
            {
                if(items[i] is Item)
                {
                    if((items[i] as Item).Name == name)
                    {
                        items[i] = default;
                    }
                }                
            }
        }
        public T FindItem(string name)
        {
            for (int i = 0; i < items.Length; i++)
            {
                if (items[i] is Item)
                {
                    if (((Item)items[i]).Name == name)
                    {
                        return items[i];
                    }
                    continue;
                }
                continue;
            }
            return default;
        }
        public void Print()
        {
            foreach(var data in items)
            {
                if(data != null)
                Console.WriteLine("ID: {0}  Name: {1}",data.Id, data.Name);
            }
        }
 
        public Inventory(int capacity)
        {
            this.items = new T[capacity];
        }
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _10._31_step1
{
    class Item
    {
        public int Id { get; private set; }
        public string Name { get; private set; }
        public Item(int id, string name)
        {
            this.Id = id;
            this.Name = name;
        }
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

:

ref 와 out

C#/Study 2019. 10. 31. 01:11
ref를 이용하면 매개변수가 인수로부터 받은 값이 초기화가 되어있다는 가정하에 그 값을 사용하게된다. 그래서 그 값이 초기화가 되어있지않으면 컴파일 에러가 발생한다.

out을 이용하면 매개변수가 인수로부터 받은 값을 메소드를 실행하면서 초기화를 하기로 약속이 되어있기때문에 굳이 초기화를 할 필요가 없는것이다.

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

12.02 객체 충돌  (0) 2019.12.02
struct 와 클래스의 차이  (0) 2019.11.02
초기화  (0) 2019.10.31
박싱과 언박싱  (0) 2019.10.31
배열 내 요소중 최대값 구하기  (0) 2019.10.15
:

초기화

C#/Study 2019. 10. 31. 00:59
초기화
데이터를 변수(공간)에 집어넣는 과정을 초기화라고 합니다.
Ex) int x = 10;
→ 이는 변수 선언과 초기화를 동시에 해준 것입니다.

 변수를 처음 만들게 되면 기존 메모리에 들어있는 값을 그대로 사용하게 되기 때문에 어떤 값이 들어있는지 알 수 없습니다. 그래서 예외 발생의 가능성이 있죠. 따라서 프로그램이 변수에 들어있는 값을 예상할 수 있는 범위 이내에 두게 하기 위해 초기화를 진행합니다.

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

struct 와 클래스의 차이  (0) 2019.11.02
ref 와 out  (0) 2019.10.31
박싱과 언박싱  (0) 2019.10.31
배열 내 요소중 최대값 구하기  (0) 2019.10.15
성적표만들기  (0) 2019.09.27
:

박싱과 언박싱

C#/Study 2019. 10. 31. 00:52
박싱과 언박싱
- object 형식은 참조 형이기 때문에 힙에 데이터를 할당한다.
- 그렇기 때문에 다른 값 형식 데이터와 저장되는 메모리 공간이 다르기 때문에 
값 형식 데이터를 힙에 할당하기 위한 “박싱(Boxing)”기능을 제공한다.
- 반대로 힙에 있던 값 형식 데이터를 다시 할당해야 하는 경우에는
“언박싱(Unboxing)” 작업이 일어난다.

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

ref 와 out  (0) 2019.10.31
초기화  (0) 2019.10.31
배열 내 요소중 최대값 구하기  (0) 2019.10.15
성적표만들기  (0) 2019.09.27
1차원 배열  (0) 2019.09.24
:

10.30 클래스로 LinkedList 구현하기 (메서드, 속성의 재귀호출)

C#/실습 2019. 10. 30. 16:41

예제:

코드:

 

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

namespace _10._30_step2
{
    class App
    {
        public App()
        {
            var list = new LinkedList();
            list.Add("홍길동");
            list.Add("정약용");
            list.Add("이호준");
            list.Add("홍길동");
            list.Add("정약용");
            list.Add("이호준");
            Console.WriteLine("인스턴스 개수: {0}",list.Count);
            Console.WriteLine("인스턴스 : ");
            list.Print();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _10._30_step2
{
    class LinkedList
    {
        public Node first;
        public Node node;
        public int count = 0;
        public int Count
        {
            get
            {
                if (first != null)
                {
                    if (node.next != null)
                    {
                        node = node.next;
                        count++;
                        return Count;
                    }
                    else
                    {
                        count++;
                        node = first;
                        return count;
                    }
                }
                return count;
            }
        }
        public LinkedList()
        {
            Console.WriteLine("LinkedList의 생성자 호출됨");
        }
        
        public void Print()
        {
            if (first != null)
            {
                if (node.next != null)
                {
                    Console.WriteLine(node.value);
                    node = node.next;
                    Print();
                }
                else
                {
                    Console.WriteLine(node.value);
                }
            }
        }
        public void Add(string data)
        {
            Node node = new Node(data);
            if (this.first == null)
            {
                this.first = node;
                this.node = node;
            }
            else
            {
                Node lastNode = FindLastNode(this.first);
                lastNode.next = node;
            }
        }
        public Node FindLastNode(Node node)
        {
            if (node.next == null)
            {
                return node;
            }
            return FindLastNode(node.next);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _10._30_step2
{
    class Node
    {
        public string value;
        public Node next;
        public Node(string data)
        {
            this.value = data;
            Console.WriteLine("새로운 노드 생성됨. (value: {0})", this.value);
        }
    }
}

 

 

여기서 주의해야 할 점은 재귀호출을 할 때이다.

재귀 호출을 한 메소드(반환타입이 있는경우)에서 return문을 사용해 메소드를 종료할 경우, 해당 재귀된 메소드가 종료되는것이지 재귀 호출한 가장 바깥의 메소드가 종료가 되는게 아니기 때문에 if문 다음에 재귀호출 후에 쓰게된 return은 결국 사용하게 된다.

반환 타입이 없는 메소드에서 return을 쓰면 가장 바깥의 메소드를 종료하지만 반환타입이 있는 경우는 for문의 break 와 같이 가장 가까운 메소드를 종료할 뿐이다.

따라서 return (재귀호출문); 을 쓰면 된다.

:

10.23 Stack 활용하기

C#/실습 2019. 10. 24. 17:39

기본적으로 Stack은 컬렉션 타입이며 Last in First Out 속성을 가지고있다.

코드:

 

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _10._23_step1
{
    class App
    {
        public App()
        {
            Stack<string> numbers;
            numbers = new Stack<string>();
            //삽입
            numbers.Push("하나");
            numbers.Push("둘");
            numbers.Push("셋");
            numbers.Push("넷");
 
            //추출
            var pop = numbers.Pop();
            Console.WriteLine(pop);
            //출력
            Console.WriteLine(numbers.Count);
            foreach(string number in numbers)
            {
                Console.WriteLine(number);
            }
            for(int i=0;i<=numbers.Count; i++)
            {
                Console.WriteLine(numbers.Pop());
            }
            while(true)
            {
                Console.WriteLine(numbers.Pop());
                if(numbers.Count == 0)
                {
                    break;
                }
            }
        }
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
:

10.23 배열에서 숫자이동시키기

C#/실습 2019. 10. 24. 17:35

0,4 위치에 있는 숫자 2를 2,0으로 옮겼다가 다시 0,4로(지그재그) 옮긴다.

코드:

 

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _10._23_step3
{
    class App
    {
        int[,] arr =
        {
            {0,0,0,0,2},
            {0,0,0,0,0},
            {0,0,0,0,0}
        };
        int count=1;
        public App()
        {
            MoveTo20(04);
            MoveTo04(20);
        }
        public void MoveTo04(int row, int col)
        {
            if (count %3!=0&& Check(row, col + 1== true && arr[row,col+1==0 )
            {
                arr[row, col + 1= arr[row, col];
                arr[row, col] = 0;
                count++;
                Print();
                MoveTo04(row, col+1);
            }
            else if(count%3==0&& Check(row-1, col)==true && arr[row-1,col]==0)
            {
                arr[row-1, col] = arr[row, col];
                arr[row, col] = 0;
                count++;
                Print();
                MoveTo04(row-1, col);
            }
        }
        public void MoveTo20(int row, int col)
        {
            if(Check(row, col - 1)==true && arr[row,col-1== 0)
            {
                arr[row, col - 1= arr[row, col];
                arr[row, col] = 0;
                Print();
                MoveTo20(row, col - 1);
            }
            else if (Check(row, col - 1== false && Check(row + 1, col) == true && arr[row + 1, col] == 0)
            {
                arr[row + 1, col] = arr[row, col];
                arr[row, col] = 0;
                Print();
                MoveTo20(row + 1, col);
            }
            
        }
        public void Print()
        {
            Console.WriteLine("--------------------");
            for (int i=0;i<arr.GetLength(0);i++)
            {
                for(int j=0;j<arr.GetLength(1);j++)
                {
                    
                    Console.Write(arr[i, j] + "\t");
                }
                Console.WriteLine();
            }
            Console.WriteLine("--------------------");
        }
        public bool Check(int nextIndexRow, int nextIndexCol)
        {
            if(nextIndexRow>=0 && nextIndexRow<3 
               && nextIndexCol>=0 && nextIndexCol<5 
               && arr[nextIndexRow, nextIndexCol]==0)
            {
                return true;
            }
            return false;
        }
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
: