객체지향
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 | using System; namespace OOP_005 { // 객체지향 프로그래밍(OOP) 기본 단위 Class // 클래스(Class) --> 패키지(Package) --> 프레임워크(Framework) // C# .NET Framework ==> PC, Enterprise, Device // OOP 1. 캡슐화 class / 멤버변수, 멤버메소드 // 2. 다형성(오버로딩, 오버라이딩) // 3. 상속 // 추상클래스, 개념적으로만 존재하고 main에서 생성되지 않는 클래스 abstract class Shape { public Shape() { Console.WriteLine("Shape 생성자 호출"); } public abstract void Draw(); } class Triangle : Shape { public Triangle() { Console.WriteLine("Triangle 생성자 호출"); } public override void Draw() { Console.WriteLine("삼각형을 그리다"); } } class Rectangle : Shape { public override void Draw() { Console.WriteLine("사각형을 그리다"); } } class Circle : Shape { public Circle() { Console.WriteLine("Circle 생성자 호출"); } public override void Draw() { Console.WriteLine("원을 그리다"); } } class Ellipse : Circle // 타원 { public Ellipse() { Console.WriteLine("Ellipse 생성자 호출"); } } class Program { static void Main(string[] args) { //Shape shape = new Shape(); // Error가 정상 <- abstract 클래스이기 때문 Triangle triangle = new Triangle(); Ellipse ellipse = new Ellipse(); } } } | 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 | using System; namespace OOP_005 { // 객체지향 프로그래밍(OOP) 기본 단위 Class // 클래스(Class) --> 패키지(Package) --> 프레임워크(Framework) // C# .NET Framework ==> PC, Enterprise, Device // OOP 1. 캡슐화 class / 멤버변수, 멤버메소드 // 2. 다형성(오버로딩, 오버라이딩) // 3. 상속 // 추상클래스, 개념적으로만 존재하고 main에서 생성되지 않는 클래스 abstract class Shape { public Shape() { Console.WriteLine("Shape 생성자 호출"); } public abstract void Draw(); } class Triangle : Shape { public Triangle() { Console.WriteLine("Triangle 생성자 호출"); } public override void Draw() { Console.WriteLine("삼각형을 그리다"); } } class Rectangle : Shape { public override void Draw() { Console.WriteLine("사각형을 그리다"); } } class Circle : Shape { public int radius; public Circle() { Console.WriteLine("Circle 생성자 호출"); } public override void Draw() { Console.WriteLine("원을 그리다"); } // 오버로딩 public virtual void Draw(int radius) { this.radius = radius; Console.WriteLine("반지름이 {0}인 원을 그리다", this.radius) ; } } class Ellipse : Circle // 타원 { public int radius; public Ellipse() { Console.WriteLine("Ellipse 생성자 호출"); } public override void Draw() { Console.WriteLine("타원을 그리다"); } public override void Draw(int radius) { } } class Program { static void Main(string[] args) { //Shape shape = new Shape(); // Error가 정상 <- abstract 클래스이기 때문 Triangle triangle = new Triangle(); Ellipse ellipse = new Ellipse(); ellipse.Draw(); ellipse.Draw(5); } } } | cs |
이번 강의에서 다루는 내용
프로퍼티
자동구현 프로퍼티
프로퍼티를 이용한 객체 초기화
무명 형식
public 필드
public 필드는 외부 객체에 의해 오염될 가능성을 열어두는 것
자바같은 언어에서는 Get/Set 메소드를 이용하여 내부 필드에 접근하도록 함
C#에서는 Get/Set 메소드뿐 아니라 필드만큼 편리한 프로퍼티를 제공
Get/Set 메소드로 필드에 접근하기
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 | using System; namespace Property { class MyClass { private int myField; public int GetMyField() { return myField; } public void SetMyField(int NewValue) { this.myField = NewValue; } } class Program { static void Main(string[] args) { MyClass obj = new MyClass(); obj.SetMyField(100); Console.WriteLine(obj.GetMyField()); } } } | cs |
프로퍼티란?
public 필드를 다루듯 내부 필드에 접근하게 해주는 멤버
외부에 데이터를 출력할 때는 get 접근자
내부에 데이터를 입력할 때는 set 접근자
자동구현 프로퍼티
프로퍼티 구현 시, 뻔하게 작성되는 코드를 생략할 수 있음
1. 필드 이름 생략
2. get접근자의 반환 문(return 필드) 생략
3. set접근자의 필드 수정 코드 생략
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 | using System; namespace Property_002 { class MyClass { private int myField; public int MyField { get { return myField; } set { myField = value; } } } class Program { static void Main(string[] args) { MyClass obj = new MyClass(); obj.MyField = 100; Console.WriteLine(obj.MyField); } } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | using System; namespace Property_002 { class MyClass { private int myField; public int MyField { get; set; } } class Program { static void Main(string[] args) { MyClass obj = new MyClass(); obj.MyField = 100; Console.WriteLine(obj.MyField); } } } | 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 | using System; namespace Property_BirthdayInfo { class BirthdayInfo { private string name; private DateTime birthday; public string Name { get; set; } public DateTime Birthday { get; set; } public int Age { get { return new DateTime(DateTime.Now.Subtract(Birthday).Ticks).Year; } } } class Program { static void Main(string[] args) { BirthdayInfo birth = new BirthdayInfo(); birth.Name = "서현"; birth.Birthday = new DateTime(1991, 6, 28); Console.WriteLine($"Name:{birth.Name}"); Console.WriteLine($"Birthday:{birth.Birthday.ToShortDateString()}"); Console.WriteLine($"Age:{birth.Age}"); } } } | 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 | using System; namespace Property_003 { class BirthdayInfo { public string Name { get; set; } = "Unknown"; public DateTime Birthday { get; set; } = new DateTime(1, 1, 1); } class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } } | 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 | using System; namespace ConstructorWithProperty { class BirthdayInfo { public string Name { get; set; } public DateTime Birthday { get; set; } public int Age { get { return new DateTime(DateTime.Now.Subtract(Birthday).Ticks).Year; } } } class Program { static void Main(string[] args) { BirthdayInfo birth = new BirthdayInfo() { Name = "서현", Birthday = new DateTime(1991, 6, 28) }; Console.WriteLine(birth.Name); Console.WriteLine(birth.Birthday.ToShortDateString()); Console.WriteLine(birth.Age); } } } | cs |
336페이지
초기화 전용(Init-Only) 자동 구현 프로퍼티
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 | using System; namespace InitOnly { class Transaction { public string From { get; init; } public string To { get; init; } public int Amount { get; init; } public override string ToString() { return $"{From,-10} -> {To,-10} : ${Amount}"; } } class Program { static void Main(string[] args) { Transaction tr1 = new Transaction { From = "Alice", To = "Bob", Amount = 100 }; Transaction tr2 = new Transaction { From = "Bob", To = "Charlie", Amount = 50 }; Transaction tr3 = new Transaction { From = "Charlie", To = "Alice", Amount = 50 }; Console.WriteLine(tr1); Console.WriteLine(tr2); Console.WriteLine(tr3); } } } | cs |
프로그램 명: dwarf(special judge)
일곱 난장이가 저녁 시간에 9 명이 와서는 모두 자기가 7 명 중에 한명이라고 우기고 있다.
난장이들은 모자를 쓰고 있고 모자에는 100 보다 작은 수가 쓰여져 있다.
다행스럽게도 일곱난장이들은 이 번호의 합이 100 이라는 것을 당신은 안다. 일곱 난장이들의 번호를 골라라.
입력
100 보다 작은 9 개의 수가 입력으로 주어진다.
출력
7 개의 수를 출력한다. 순서는 관계가 없다.
입출력 예
입력
7
8
10
13
15
19
20
23
25
출력
7
8
10
13
19
20
23
입력
8
6
5
1
37
30
28
22
36
출력
8
6
5
1
30
28
22
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 | using System; namespace Quiz_dwarf { class Program { static void Main(string[] args) { int[] arr = new int[9]; for(int i = 0; i < 9; i++) { arr[i] = int.Parse(Console.ReadLine()); } int sum = 0; int n1 = 0; int n2 = 0; for (int i = 0; i < arr.Length; i++) { sum += arr[i]; } for (int i = 0; i < arr.Length; i++) { for (int j = 0; j < arr.Length - i; j++) { int twosum = 0; twosum = arr[i] + arr[i + j]; if (j == 0) continue; if (twosum == (sum - 100)) { n1 = i; n2 = i + j; } } } Console.WriteLine(); for (int i = 0; i < arr.Length; i++) { if ((i == n1) || (i == n2)) { continue; } Console.WriteLine(arr[i]); } } } } | 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 | using System; namespace Record { record RTransaction { public string From { get; init; } public string To { get; init; } public int Amount { get; init; } public override string ToString() { return $"{From,-10} -> {To,-10} : ${Amount}"; } } class Program { static void Main(string[] args) { RTransaction tr1 = new RTransaction() { From = "Alice", To="Bob", Amount = 100 }; RTransaction tr2 = new RTransaction() { From = "Alice", To = "Charlie", Amount = 100 }; Console.WriteLine(tr1); Console.WriteLine(tr2); } } } | cs |
배열(Array)
같은 형식의 복수 인스턴스를 저장할 수 있는 형식
참조형식으로써 연속된 메모리 공간을 가리킴
반복문, 특히 for/foreach문과 함께 사용하면 효율 향상
꺾쇠 괄호 [] 안에 배열의 크기를 지정하여 다음과 같이 선언
데이터형식[] 배열이름 = new 데이터형식[용량];
int[] array = new int[5];
배열의 초기화 방법
기본 : 배열의 원소 개수 명시
요소 개수 : 생략 배열의 요소 개수 생략
new 연산자, 형식, 요소개수 생략 : new 연산자, 형식과 갈호 [와 ], 배열의 용량을 모두 생략
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | using System; namespace Array_001 { class Program { static void Main(string[] args) { string[] array1 = new string[3] { "안녕", "Hello", "Halo" }; string[] array2 = new string[] { "안녕", "Hello", "Halo" }; string[] array3 = { "안녕", "Hello", "Halo" }; int[] array4 = { 1, 2, 3 }; // 선언 OK for(int i = 0; i < array1.Length; i++) Console.WriteLine(array1[i]); foreach (string s in array2) Console.WriteLine(s); foreach (int n in array4) Console.WriteLine(n); } } } | 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 | using System; namespace Array_001 { class Program { static void Main(string[] args) { string[] array1 = new string[3] { "안녕", "Hello", "Halo" }; string[] array2 = new string[] { "안녕", "Hello", "Halo" }; string[] array3 = { "안녕", "Hello", "Halo" }; int[] array4 = { 1, 2, 3 }; // 선언 OK for(int i = 0; i < array1.Length; i++) Console.WriteLine(array1[i]); foreach (string s in array2) Console.WriteLine(s); foreach (int n in array4) Console.WriteLine(n); // 10.3 System.Array Console.WriteLine($"array1 Type : {array1.GetType()}"); Console.WriteLine($"Base type of array : {array1.GetType().BaseType}"); int a = 100; Console.WriteLine($"a Type : {a.GetType()}"); Console.WriteLine($"Base type of a : {a.GetType().BaseType}"); byte b = 1; Console.WriteLine($"b Type : {b.GetType()}"); Console.WriteLine($"Base type of b : {b.GetType().BaseType}"); double d = 3.14; Console.WriteLine($"d Type : {d.GetType()}"); Console.WriteLine($"Base type of d : {d.GetType().BaseType}"); } } } | cs |
366페이지
System.Array 클래스
모든 배열의 기반 클래스이며 배열 그 자체를 나타냄
배열을 보다 편리하게 다룰 수 있게 도와주는 유틸리티 메소드 제공
정렬, 탐색, 크기 조정 등의 기능 제공
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | using System; namespace Array_Test_001 { class Program { static void Main(string[] args) { int[] score = new int[] {9, 8, 7, 6, 5, 4, 3, 2, 1}; foreach (int i in score) Console.Write(i + ""); Console.WriteLine(); Array.Sort(score); foreach (int i in score) Console.Write(i + ""); Console.WriteLine(); } } } | 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 | using System; namespace Quia_Bubble { class Program { static void Main(string[] args) { string[] splitmp = Console.ReadLine().Split(' '); int n = int.Parse(splitmp[0]); int s = int.Parse(splitmp[1]); string[] splitmp2 = Console.ReadLine().Split(' '); int[] number = new int[n]; for(int i = 0; i < n; i++) { number[i] = int.Parse(splitmp2[i]); } for(int i = 0; i < number.Length; i++) { for(int j = 0; j < (number.Length-1); j++) { if (number[j] > number[j + 1]) { int tmp = number[j]; number[j] = number[j + 1]; number[j + 1] = tmp; } } Console.Write("{0}단계 : ", i + 1); foreach (int a in number) Console.Write(a + " "); Console.WriteLine(); } } } } | 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 | using System; namespace Quiz_MySelection { class Program { static void Main(string[] args) { string[] splitmp = Console.ReadLine().Split(' '); int n = int.Parse(splitmp[0]); int s = int.Parse(splitmp[1]); string[] splitmp2 = Console.ReadLine().Split(' '); int[] number = new int[n]; for (int i = 0; i < n; i++) { number[i] = int.Parse(splitmp2[i]); } for (int i = 0; i < s; i++) { int minindex = i; for (int j = i + 1; j < number.Length; j++) { if (number[minindex] > number[j]) { minindex = j; } } int tmp = number[minindex]; number[minindex] = number[i]; number[i] = tmp; Console.Write("{0}단계 : ", i + 1); foreach (int a in number) Console.Write(a + " "); Console.WriteLine(); } } } } | cs |
'C#' 카테고리의 다른 글
| 스마트팩토리 4주 16일차 C# 10일차 (0) | 2021.05.18 |
|---|---|
| 스마트팩토리 4주 15일차 C# 9일차 (0) | 2021.05.17 |
| 스마트팩토리 3주 13일차 C# 7일차 (0) | 2021.05.13 |
| 스마트팩토리 3주 12일차 C# 6일차 (0) | 2021.05.12 |
| 스마트팩토리 3주 11일차 C# 5일차 C# (0) | 2021.05.11 |




최근댓글