2013년 8월 30일 금요일

제네릭 형식 정의와 사용

1. using System.Collections.Generic
2. 제한 사항과 제약 사항
   
제한사항 
  1. 제네릭이 적용된 클래스는 ContextBoundObject 클래스로부터 파생될 수 없다.
  2. 열거형에 사용될 수 없다.
  3. Replection을 이용해서 생성되는 동적 메서드는 제네릭 형식을 취할 수 없다.
 -제약사항 : 제네릭 클래스 레벨에서 선언될 경우 선언하는 클래스에 몇 가지의 제약 사ㅏ항을 지정할 수 있다.  이 제약 사항은 SQL문에서 where절에서 사용하는 것과 의미가 동일하다.
예 :

//IDisposable을 구현하는 T
class GenericConstraint<T> where T : IDisposable{}
//class 타입 T, 구조체 타입 U
class GenericConstraint<T, U> where T : class where U : struct{}
//IComparable을 구현하고, 파라미터가 없는 기본 생성자를 가진 타입 T
class GenericConstraint<T> where T : IComparable, new()

//델리게이터에 파라미터가 없는 기본생성자를 가진 타입 T
delegate T GenericDelegate<T>(T val) where T : new();

Dictionary<TKey, TValue>
Dictionary<int, string> colorDic = new Dictionary<int, string>();
//key와 value를 쌍으로 저장
colorDic.Add(1, "Red");
//값 변경
colorDic[1] = "Black";
//key가 3인 color 값 조회
string blackColor = string.Empty;
if(colorDic.TryGetValue(3, out blackColor))
{
    Console.WriteLine("key가 3으로 저장된 Color는 {0}", blackColor);
}
//key가 4인 데이터 존재 유무 확인
if(!colorDic.ContainsKey(4))
{
    colorDic.Add(4, "Yellow");
}
//key값만 가지는 컬렉션 객체 생성
Dictionary<int, string>.KeyCollection keyCollection = colorDic.Keys;
foreach(int key in keyCollection)
{
    Console.WriteLine(key);
}
//value값만 가지는 컬렉션 객체 생성
Dictionary<int, string>.ValueCollection valueCollection = colorDic.Values;
//key와 value를 쌍으로 가지는 컬렉션의 요소 조회
foreach(KeyValuePair<int, string> keyValue in colorDic)
{
    Console.WriteLine("key {0}의 Color는 {1}", keyValue.Key, keyValue.Value); 
}
*TryGetValue 메서드는 key값을 기준으로 해당 데이터를 out파라미터로 전달한다.
List<T>
예:
List<int> list = new List<int>();
list.Add(100);
//컬렉션의 현재 배열 크기 조회
Console.WriteLine("컬렉션의 현재 배역 크기는 {0}", list.Capacity);
//컬렉션의 현재 저장 데이터 개수 조회
Console.WriteLine("컬렉션에 저장된 요소의 개수는 {0}", list.Count);
//1번째에 데이터 저장
list.Insert(1, 500);
//1번째에 저장된 데이터 조회
Console.WriteLine("1번째 데이터는 {0}", list[1]);
//1번째에 데이터 삭제
list.RemoveAt(1);
//컬렉션의 배열 크기를 조정
list.TrimExcess();
TrimExcess() : 동적 배열 크기를 갖는 클래스에서 공통적으로 사용되는 메서드로 호출후의 배열 크기는 컬렉션에 저장되어 있는 요소의 개수와 동일해 진다.
SortedList<TKey, TValue>
예:
// 컬렉션 인스턴스 생성
SortedList<int, string> colorSort = new SortedList<int, string>();
// 데이터 저장
colorSort.Add(1, "Red");
colorSort.Add(3, "Green");
colorSort.Add(2, "Blue");
// 저장된 데이터 조회
foreach (KeyValuePair<int, string> color in colorSort)
{
    Console.WriteLine(color.Value);
}
// 컬렉션의 배열 크기 조회
Console.WriteLine("현재 컬렉션의 배열 크기 : {0}", colorSort.Capacity);
// 컬렉션 배열 크기 조정
colorSort.TrimExcess();
// 첫 번째 배열 크기 및 요소 개수 조회
Console.WriteLine("첫 번째 TrimExcess 호출 후 컬렉션 배열 크기:{0}, 요소 개수:{1}", colorSort.Capacity, colorSort.Count);
// key 값이 2인 데이터 삭제
colorSort.RemoveAt(2);
// 컬렉션 배열 크기 조정
colorSort.TrimExcess();
// 두 번째 배열 크기 및 요소 개수 조회
Console.WriteLine("두 번째 TrimExcess 호출 후 컬렉션 배열 크기:{0}, 요소 개수:{1}", colorSort.Capacity, colorSort.Count );

LinkedList<T>
Queue<T>
Stack<T>

댓글 없음:

댓글 쓰기