Reflection 은 모든 클래스가 상속받는 object의 속성들을 이용하여 동적으로 객체를 생성할 때 사용할 수 있다.
간단하게 Generic 클래스의 객체와 generic 함수를 reflection을 이용하여 생성하는 방법이다.
namespace ReflectIt
{
class Program
{
static void Main(string[] args)
{
var employeeList = CreateCollection(typeof(List<>), typeof(Employee));
Console.Write(employeeList.GetType().Name);
var genericArgs = employeeList.GetType().GetGenericArguments();
foreach (var arg in genericArgs)
{
Console.Write("[{0}]",arg.Name);
}
Console.WriteLine();
var employee = new Employee();
var employeeType = typeof(Employee);
var methodInfo = employeeType.GetMethod("Speak");
methodInfo = methodInfo.MakeGenericMethod(typeof(DateTime));
methodInfo.Invoke(employee, null);
}
private static object CreateCollection(Type collectionType, Type itemType)
{
var closedType = collectionType.MakeGenericType(itemType);
return Activator.CreateInstance(closedType);
}
}
public class Employee
{
public string Name { get; set; }
public void Speak()
{
Console.WriteLine(typeof(T).Name);
}
}
}
Container Class with Generic
generic을 사용하는 container 패턴의 코드를 만드는 방법이다.
container 디자인 패턴은 입력받은 클래스의 형식을 지정된 클래스로 반환하는 클래스를 말하는 것 같다..(아직 공부중..)
이때 Generic 클래스에 대한 반환을 위한 방법들이 기술된 코드이다.. (참고 : PluralSight 의 C# generic의 tutorial 코드이다)
코드는 첨부로..
코드에 해당 내용에 대한 이해되는 부분들을 나름 주석으로 넣음.