■ 지정한 타입의 항목을 갖는 제네릭 리스트 구하기
------------------------------------------------------------------------------------------------------------------------
▶ Program.cs
using System; using System.Collections.Generic;
namespace TestProject { /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private
#region 프로그램 시작하기 - Main()
/// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { Console.Title = "지정한 타입의 항목을 갖는 제네릭 리스트 구하기";
List<Item> sourceList = new List<Item>() { Item.A, Item.B };
Type itemType = sourceList.GetType().GetGenericArguments()[0];
dynamic list = GetGenericList(itemType);
list.Add(Item.A);
Console.WriteLine("항목 타입 : {0}", itemType ); Console.WriteLine("리스트 타입 : {0}", list.GetType()); Console.WriteLine("첫번째 항목 : {0}", list[0] ); }
#endregion
#region 제네릭 리스트 구하기 - GetGenericList(itemType)
/// <summary> /// 제네릭 리스트 구하기 /// </summary> /// <param name="itemType">항목 타입</param> /// <returns>제네릭 리스트</returns> private static dynamic GetGenericList(Type itemType) { Type genericListType = typeof(List<>);
Type targetListType = genericListType.MakeGenericType(new Type[] { itemType });
object targetListObject = Activator.CreateInstance(targetListType);
return targetListObject; }
#endregion } }
|
------------------------------------------------------------------------------------------------------------------------
'C# > Common' 카테고리의 다른 글
[C#/COMMON] CancellationToken 클래스 : 작업 취소시키기 (0) | 2019.08.03 |
---|---|
[C#/COMMON] WM_DEVICECHANGE 메시지를 사용해 USB 연결/해제 알림 구하기 (0) | 2019.08.03 |
[C#/COMMON] WindowsIdentity 클래스 : 윈도우즈 로그인 계정 구하기 (0) | 2019.08.02 |
[C#/COMMON] 인증서 설치하기 (0) | 2019.08.02 |
[C#/COMMON] IMessageFilter 인터페이스 : WM_INPUT 메시지 처리하기 (0) | 2019.08.02 |
[C#/COMMON] 지정한 타입의 항목을 갖는 제네릭 리스트 구하기 (0) | 2019.08.01 |
[C#/COMMON] 콘솔(Console) 프로그램 CTRL+C 종료시 처리하기 (0) | 2019.08.01 |
[C#/COMMON] 커스텀 태스크 사용하기 (0) | 2019.08.01 |
[C#/COMMON] 커스텀 태스크 사용하기 (0) | 2019.08.01 |
[C#/COMMON] IAsyncStateMachine 인터페이스 : 비동기 처리하기 (0) | 2019.07.31 |
[C#/COMMON] IAsyncStateMachine 인터페이스 : 비동기 처리하기 (0) | 2019.07.31 |
댓글을 달아 주세요