2018년 11월 2일 금요일

C# - 이름으로 객체 생성 2

밑에 C#에서 이름으로 객체를 생성하는 방법이 있습니다만, 가끔 이런 코드가 불가능한 경우가 있습니다. 특히 모바일용 Portable 코드를 사용할 때 말입니다.

using System.Reflection;

namespace ClassName
{
    internal class ClassA
    {
        internal void Write()
        {
            Console.WriteLine("ClassA");
        }
    }
    internal class ClassB
    {
        internal void Write()
        {
            Console.WriteLine("ClassB");
        }
    }
}

이런 상황에서는 대부분 Assembly의 GetExcutingAssembly 함수를 사용할 수가 없습니다.
이 경우에는 이런 식으로 사용할 수가 있죠.

    string className = "ClassName.ClassA";
    Type type = Type.GetType(className);
    if (type == null)
        throw new NotImplementedException();
    object obj = Activator.CreateInstance(type);
    var myClass = obj as SpObj.CompAI.AIBrain;
    if (myClass == null)
        throw new NotImplementedException();