Chapter11. 일반화 프로그래밍
1. 일반화 프로그래밍
> 일반화 프로그래밍이란 구조가 똑같은 클래스와 메서드의 데이터 형식을 일반화(T 치환)하는 것을 말함.
1) 일반화 메서드
한정자 반환형 메서드 <형식> (매개변수)
public void Copy<T>(T value, T value2)
public void CopyArray<T> (T[] value, T[] value2) // 일반화 메서드
{
for(int i=0; i< value.Length; i++)
value[i] = value2[i];
}
int[] num = {1, 2, 3, 4, 5};
int[] num2 = new int[value.Length];
CopyArray<int>(num, num2); // 일반화 메서드 호출
foreach (int e in num2)
Console.WriteLine(e);
2) 일반화 클래스
class 클래스 <형식>
{}
class Array<T>
{}
class Array_Standard<T> // 일반화 클래스
{
private T[] array;
public T GetArray(int index)
{
return array[index];
}
}
Array_Standard<double> dbArr = new Array_Standard<double>(); // 일반화 클래스를 이용해 객체 생성
2. 형식 매개변수 제약시키기
> 앞에서 배운 형식 <T>를 일정한 조건으로 제약시키기 위한 문법임
> where 절을 사용한다
1) 기본문법
class MyList<T> where T : 제약조건 // 일반화 클래스의 형식 제약
{
...
}
void CopyArray<T>(T[] source, T[] target) where T : 제약조건 // 일반화 메서드의 형식 제약
{
...
}
2) 제약조건
- where T : struct : T는 값 형식이어야 함 ▼
class MyList<T> where T : MyClass
{
...
}
- where T : class : T는 참조 형식이어야 함 ▼
class CopyArray<T>(T[] source, T[] target) where T : struct
{
...
}
- where T : 기반클래스 : T는 기반 클래스의 파생 클래스여야 함
- where T : 인터페이스 : T는 인터페이스를 반드시 구현하여야 함
- where T : new() : T는 매개변수가 없는 생성자가 있어야 함 ▼
public static T CreateInstance<T>() where T : new()
{
return new T();
}
- where T : U : T는 U로부터 상속받은 클래스여야 함 > 일반화 메서드에서 사용 ▼
class BaseArray<U> where U : Base // where T : 기반클래스 와 같음
{
public U[] Array { get; set; }
public void CopyArray<T>(T[] source) where T : U // where T : U
{
source.CopyTo(Array, 0);
}
}
3. 일반화 컬렉션
> 이전의 ArrayList, Queue, Stack, Hashtable을 일반화한 것
1) List<T>
> T(형식)으로만 입력할 수 있음
List<int> list = new List<int>(); // 생성
for(int i=1; i<6; i++) // Add
list.Add(i);
list.RemoveAt(2); // RemoveAt
list.Insert(2, 100); // Insert
2) Queue<T>
Queue<int> queue = new Queue<int>();
for(int i=1; i<6; i++)
queue.Enqueue(i); // Enqueue
while(queue.Count > 0)
Console.WriteLine(queue.Dequeue()); // Dequeue
3) Stack<T>
Stack<int> stack = new Stack<int>();
for(int i=1; i<6; i++)
stack.Push(i); // Push
while(stack.Count > 0)
Console.WriteLine(stack.Pop()); // Pop
4) Dictionary<TKey, TValue>
> Hashtable의 일반화 버전
Dictionary<string, string> dic = new Dictionary<string, string>();
dic["하나"] = "one";
dic["둘"] = "two";
dic["셋"] = "three";
dic["넷"] = "four";
dic["다섯"] = "five"; // 저장
Console.WriteLine(dic["하나"]);
Console.WriteLine(dic["둘"]);
Console.WriteLine(dic["셋"]);
Console.WriteLine(dic["넷"]);
Console.WriteLine(dic["다섯"]); // 출력
Chapter12. 예외 처리하기
1. try~catch
> try로는 실행을, catch로는 예외를 잡아 그에 따른 처리를 하기 위한 문법
try
{
// 실행코드
}
catch(예외객체)
{
// 예외시 실행코드
}
try
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine(arr[i]);
}
}
catch (Exception e)
{
Console.WriteLine($"예외 발생 : {e.Message}");
}
▲ Exception 클래스는 모든 예외를 처리할 수 있는 클래스.
> 하지만 개발자가 의도한 예외를 포함해서 모든 예외를 다 잡아버리기 때문에 실제 의도와 다르게 예외를 처리해버릴 수 있는단점이 있다.
try
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine(arr[i]);
}
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine($"예외 발생 : {e.Message}");
}
▲ IndexOutOfRangeExcepiton 클래스는 Exception 클래스로부터 상속을 받은 클래스로 잘못된 인덱스로 배열의 요소에 접근하려 할 때 예외를 담는 클래스임.
2. 예외 던지기(throw)
> 이전까지는 catch로 예외를 잡기만 했는데, 지금부터는 throw로 예외를 던질 수 있다.
try
{
...
throw new Exception("예외를 던집니다"); // 예외를 던지고(throw)
}
catch(Exceptin e) // 잡는다(catch)
{
Console.WriteLine(e.Message);
}
▲ throw문
int? a = null; // a는 int 또는 null을 담을 수 있는 형태, 여기서는 null을 담음
int b = a ?? throw new ArgumentNullException(); // a가 null이 아니라면 b에 담고, null 이라면 뒤의 throw식 실행
int[] arr = new[] {1, 2, 3};
int index = 4;
int value = arr[index >= 0 && index < 3 ? index : throw new IndexOutOfRangeException()];
// index가 0 이상이고 3 미만이면 index를 그 외에는 throw식 실행
3. finally
> finally는 예외처리 때문에 미처 실행하지 못할 수 있는 이후 실행부분을 무조건 실행해주는 문법임(마무리)
try
{
// 실행
}
catch(Exception e)
{
// 예외처리
}
finally
{
// 마무리
}
static int nums(int num1, int num2)
{
try
{
return 1; // try가 모두 처리되어도 finally는 실행됨
}
catch (Exception e)
{
throw e; // catch로 예외처리가 되어도 finally는 실행됨
}
finally
{
Console.WriteLine("끝");
}
}
▲ 어떠한 경우도 finally 안에 있는 마무리는 실행된다.
'LMS 7 > 개발일지' 카테고리의 다른 글
| 25.09.30 개발일지 / C# 클래스 (0) | 2025.11.11 |
|---|---|
| 25.09.29 개발일지 / C# 3 (Chapter13) (0) | 2025.11.11 |
| 25.09.28 개발일지 / C# 2(2) (Chapter09, Chapter10) (0) | 2025.11.11 |
| 25.09.27 개발일지 / C# 2(1) (Chapter07, Chapter08) (0) | 2025.11.11 |
| 25.09.26 개발일지 / C# 1(1) (Chapter02~Chapter03) (0) | 2025.11.11 |