Generic
내용
- 컴파일 타임에 데이터 타입을 지정할 수 있는 기능
- 타입 안전성 보장
- 런타임 캐스팅이 필요 없어 성능 유리해짐
- 코드 재사용성 높임
샘플 코드 - Generic class
// Generic 클래스 정의
public class Box<T> // T는 임의의 타입 매개변수 ex. int, string
{
private T _content;
public void SetContent(T content)
{
_content = content;
}
public T GetContent()
{
return _content;
}
}
// Generic 클래스 사용
public class Program
{
public static void Main()
{
Box<int> intBox = new Box<int>();
intBox.SetContent(123);
Console.WriteLine(intBox.GetContent()); // 출력: 123
Box<string> stringBox = new Box<string>();
stringBox.SetContent("Hello");
Console.WriteLine(stringBox.GetContent()); // 출력: Hello
}
}
샘플 코드 - Generic Method
public class Program
{
public static void Print<T>(T input) // T는 메서드에서 사용할 타입 매개변수
{
Console.WriteLine(input);
}
public static void Main()
{
Print<int>(10); // 출력: 10
Print<string>("Test"); // 출력: Test
}
}
샘플 코드 - where 절로 Generic 타입 제한
// where 키워드를 사용하여 T 타입 제한
public class Repository<T> where T : class // T는 참조 타입만 가능
{
private T _data;
public void Save(T data) => _data = data;
public T Load() => _data;
}
Collection
내용
- 데이터를 저장, 관리, 검색하기 위한 컨테이너 또는 데이터 구조
- Non-Generic collection, Generic collection으로 구분
Non-Generic Collection
- 타입 제한이 없으며, object로 데이터를 저장
- Generic이 도입되기 전의 방식으로 가져올 때 캐스팅이 필요
- 타입 안정성이 없고 런타임 에러 가능성 존재
//ArrayList 예시
using System.Collections;
ArrayList list = new ArrayList();
list.Add(1);
list.Add("Hello");
list.Add(3.14);
int num = (int)list[0]; // 캐스팅 필요
string text = (string)list[1];
Generic Colleciton
- 데이터 타입을 지정할 수 있는 Collection
- 타입 안정성 보장하며 캐스팅이 필요 없음
using System.Collections.Generic;
List<int> numbers = new List<int>(); // <> -> Generic 기호
numbers.Add(1);
numbers.Add(2);
// numbers.Add("Hello"); // 컴파일 에러
Console.WriteLine(numbers[0]); // 출력: 1
결론
Generic은 특정 데이터 타입을 동적으로 처리할 수 있도록 클래스와 함수에서 사용가능하고, 코드 재사용성 증가
Collection은 데이터를 저장, 관리, 검색하기 위한 데이터 구조로써 데이터를 효율적으로 관리하기 위해 사용
'C# > 공통' 카테고리의 다른 글
[JSON] C#에서의 JSON 핸들링 with Newtonsoft.Json (0) | 2025.01.14 |
---|---|
[C#] NPOI를 이용한 Excel 파일 쓰기, 읽기 (0) | 2024.03.07 |