C# 문법종합반 3주차 과제 완성하고 너덜너덜해져서 4주차 강의 듣기 시작. . .
과제 TIL 먼저 써야 되는데 진짜 너ㅁㅜ 귀찮으니까.. 이따 쓸래.............,,
interface IMyInterface
{
void Method1();
int Method2(string str);
}
class MyClass : IMyInterface
{
public void Method1()
{
// 구현
}
public int Method2(string str)
{
// 구현
return 0;
}
}
public interface IUsable
{
void Use();
}
public class Item : IUsable
{
public string Name { get; set; }
public void Use()
{
Console.WriteLine("아이템 {0}를 사용했습니다.", Name);
}
}
public class Player
{
public void UserItem(IUsable item)
{
item.Use();
}
}
static void Main(string[] args)
{
Player player = new Player();
Item item = new Item() { Name = "Health Potion" }; // 매개변수가 아님. 초기화를 위해 값을 미리 세팅한 것
player.UserItem(item);
}
public interface IItemPickable
{
void PickUp();
}
public interface IDroppable
{
void Drop();
}
public class Item : IItemPickable, IDroppable
{
public string Name { get; set; };
public void PickUp()
{
Console.WriteLine("아이템 {0}을 주웠습니다.", Name);
}
public void Drop()
{
Console.WriteLine("아이템 {0}을 버렸습니다.", Name);
}
}
public class Player
{
public void InteractWithItem(IItemPickable item)
{
item.PickUp();
}
public void DropItem(IDroppable item)
{
item.Drop();
}
}
static void Main()
{
Player player = new Player();
Item item = new Item { Name = "Sword" };
player.InteractWithItem(item);
player.DropItem(item);
}
인터페이스 | 추상클래스 | |
---|---|---|
특징 | 추상적인 동작만 정의 구현을 갖지 않음 | 일부 동작의 구현을 가짐 추상 메서드를 포함할 수 있음 단일 상속만 가능 다른 클래스와 계층 구조 형성 가능 |
장점 | 클래스 간의 결합도 ↓ 유연한 상호작용, 코드 재사용성, 확장성 ↑ | 코드 중복 방지 확장성 제공 |
단점 | 인터페이스를 구현하는 클래스는 모든 동작을 구현해야 하므로 작업량 증가 | 다중 상속 불가능 유연성 제한 |
enum MyEnum
{
Value1 = 10,
Value2, // 지정하지 않으면 바로 앞 숫자 + 1
Value3 = 20
}
MyEnum myEnum = MyEnum.Value1;
int intValue = (int)MyEnum.Value1;
MyEnum enumValue = (MyEnum)intValue;
switch (enumValue)
{
case MyEnum.Value1:
// Value1 처리
break;
case MyEnum.Value2:
// Value2 처리
break;
case MyEnum.Value3:
// Value3 처리
break;
default:
// 기본 처리
break;
}
public enum Month
{
Jan = 1,
Feb,
Mar,
Apr,
May,
Jun,
Jul,
Aug,
Sep,
Oct,
Nov,
Dec
}
public static void ProcessMonth(int month)
{
if (month >= (int)Month.Jan && month <= (int)Month.Dec)
{
Month selectMonth = (Month)month;
Console.WriteLine("선택한 월은 {0}입니다.", selectMonth);
} else
{
Console.WriteLine("올바른 월을 입력해주세요.");
}
}
static void Main(string[] args)
{
int userInput = 7;
ProcessMonth(userInput);
}
try-catch 블록을 사용하여 구현
try
{
// 예외가 발생할 수 있는 코드
}
catch (ExceptionType1 ex)
{
// ExceptionType1에 해당하는 예외 처리
}
catch (ExceptionType2 ex)
{
// ExceptionType2에 해당하는 예외 처리
}
finally
{
// 예외 발생 여부와 관계없이 항상 실행되는 코드
}
catch 블록의 우선순위
다중 catch 블록
예외 객체
try
{
int result = 10 / 0; // ArithmeticException 발생
Console.WriteLine("결과 : " + result);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("0으로 나눌 수 없습니다.");
}
catch (Exception ex)
{
Console.WriteLine("예외가 발생했습니다 : " + ex.Message);
}
finally
{
Console.WriteLine("finally 블록이 실행되었습니다.");
}
public class NegativeNumberException : Exception
{
// 부모에게 message를 전달해서 먼저 실행 후 내가 정의한 예외 처리를 실행
public NegativeNumberException(string message) : base(message)
{
}
}
try
{
int number = -10;
if (number < 0)
{
throw new NegativeNumberException("음수는 처리할 수 없습니다.");
}
}
catch (NegativeNumberException ex)
{
Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("예외가 발생했습니다 : " + ex.Message);
}
// 플레이어 이동
try
{
// 플레이어 이동 코드
if (IsPlayerCollidingWithWall())
{
throw new CollisionException("플레이어가 벽에 충돌했습니다.");
}
}
catch (CollisionException ex)
{
// 충돌 예외 처리
Debug.Log(ex.Message);
...
}
// 리소스 로딩
try
{
// 리소스 로딩 코드
LoadResource("image.png");
}
catch (ResourceNotFoundException ex)
{
// 리소스가 없는 경우 예외 처리
Debug.Log(ex.Message);
...
}
catch (ResourceLoadException ex)
{
// 리소스 로딩 중 오류 발생한 경우 예외 처리
Debug.Log(ex.Message);
...
}
// 게임 상태 전이
try
{
// 상태 전이 코드
if (currentGameState != GameState.Playing)
{
throw new InvalidStateException("게임 실행 중이 아닙니다!");
}
}
catch (InvalidStateException ex)
{
// 상태 예외 처리
Debug.Log(ex.Message);
...
}
값형 (Value Type) | 참조형 (Reference Type) | |
---|---|---|
변수 저장 방식 | 변수에 값을 직접 저장 -> 변수가 실제 데이터를 보유 | 변수가 데이터에 대한 참조(메모리 주소)를 저장 |
변수 할당/전달 | 값이 복사 | 참조가 복사 |
예시 | int, float, double, bool 등 기본 데이터 타입 | 클래스, 배열, 인터페이스 |
static void Main()
{
// 값형
int x = 10;
int y = x;
y = 20;
Console.WriteLine("x: " + x); // 10
Console.WriteLine("y: " + y); // 20
// 참조형
int[] arr1 = new int[] {1, 2, 3, 4};
int[] arr2 = arr1;
arr2[0] = 4;
Console.WriteLine("arr1[0]: " + arr1[0]); // 4
Console.WriteLine("arr2[0]: " + arr2[0]); // 4
// 박싱과 언박싱
int num1 = 10;
object obj = num1; // 박싱
int num2 = (int)obj; // 언박싱
Console.WriteLine("num1: " + num1); // 10
Console.WriteLine("num2: " + num2); // 10
}
리스트 활용 예제
List<object> myList = new List<object>();
int intValue = 10;
myList.Add(intValue); // int -> object 박싱
float floatValue = 3.14f;
myList.Add(floatValue); // float -> object 박싱
int value1 = (int)myList[0]; // object -> int 언박싱
float value2 = (float)myList[1]; // object -> float 언박싱
너무 길어서 나머지는 다음 TIL로 ~~
개발자로서 배울 점이 많은 글이었습니다. 감사합니다.