Reflection : 객체 이름으로 객체 생성하기.

Main 함수 

using System;
using System.Collections.Generic;
namespace Study
{
    class Program
    {
        static void Main(string[] args)
        {
            // IAnimal 리스트
            var list = new List<IAnimal>();
            
            // type.GetType 으로 Cat 객체 생성
            var animal = Type.GetType("Study.Cat");
            var cat = Activator.CreateInstance(animal) as Cat;
            cat.Name = "고양이";
            list.Add(cat);
            
            
            // type.GetType 으로 Dog 객체 생성
            animal = Type.GetType("Study.Dog");
            var dog = Activator.CreateInstance(animal) as Dog;
            dog.Name = "강아지";
            list.Add(dog);
            
            // 결과 출력
            foreach(var r in list)
            {
             	Console.WriteLine($" name : {r.Name}, Type : {r.GetType()}");
            }
        }
    }
}

 

IAnimal 인터페이스 

using System;
using System.Collections.Generic;
using System.Text;

namespace Study
{
    public interface IAnimal
    {
        string Name { get; set; }
    }
}

 

 IAnimal 자식 객체들

using System;
using System.Collections.Generic;
using System.Text;

namespace Study
{
	// 고양이
    public class Cat : IAnimal
    {
        public string Name { get; set; }
    }
	// 개
    public class Dog : IAnimal
    {
        public string Name { get; set; }
    }
}

 

실행 결과