https://docs.microsoft.com/ko-kr/dotnet/csharp/fundamentals/types/generics
Generic classes and methods
Learn about generics. Generic types maximize code reuse, type safety, and performance, and are commonly used to create collection classes.
docs.microsoft.com
*제너릭(Generics) 클래스 및 메서드
-정확한 데이터 형식에 맞게 조정 가능
ArrayList -> List<T>
Hashtable -> Dictionary<TKey, TValue> 를 사용
----------------------------
public class Generic<T>
{
public T Field;
}
---------------------------
Generic<string> g = new Generic<string>();
g.Field = "홍길동"; -> 문자열로만 받을 수 있다(정수x)
using System;
using System.Collections;
using System.Collections.Generic; //제너릭을 사용하기 위해 추가
namespace Helloworld
{
class Program
{
static void Main(string[] args)
{
ArrayList arrayList = new ArrayList(); //컬렉션을 초기화
arrayList.Add(1);
arrayList.Add("홍길동");
arrayList.Add(new Item());
int num = (int)arrayList[0]; //unboxing
foreach(object obj in arrayList)
{
Console.WriteLine(obj);
}
//ArrayList -> List<T>
//T 형식 매개변수
List<int> list; //리스트 변수 선언
//초기화
list = new List<int>();
//값 추가
list.Add(1);
list.Add(203);
int num2 = list[0];
list[0] = 123;
foreach(int element in list)
{
Console.WriteLine(element);
}
for(int i = 0; i < list.Count; i++)
{
Console.WriteLine(list[i]);
}
Console.WriteLine("count: {0}", list.Count);
}
}
}
'c# > 수업 내용' 카테고리의 다른 글
예외 및 예외 처리 (try-catch-finally) (0) | 2021.09.06 |
---|---|
데이터 테이블 과 Dictionary (연습 문제) (0) | 2021.09.03 |
C# 인덱서 이론과 기본 문제 (0) | 2021.09.03 |
스택 연습문제 (문자열 뒤집기) (0) | 2021.09.02 |
Hachtable 클래스와 기본 문제 (0) | 2021.09.02 |