동적으로 게임 캐릭터를 생성한다.

이름, 체력(Hp), 마나(Mp), 공격력(Atk), 방어력(Def)을 필드로 가지는 Profile 클래스 인스턴스를 동적으로 생성하고 그 프로퍼티에 동적으로 할당하는 것으로, 게임 내에서 런타임에도 새로운 캐릭터를 생성할 수 있도록 한다.

using System;
using System.Reflection;

namespace NewCharacter
{
    class Profile
    {
        private string name;
        private int hp;
        private int mp;
        private int atk;
        private int def;
        public Profile()
        {
            name = "";
            hp = 0;
            mp = 0;
            atk = 0;
            def = 0;
        }

        public Profile(string name)
        {
            this.name = name;
            this.hp = 100;
            this.mp = 50;
            this.atk = 10;
            this.def = 5;
        }

        public Profile(string name, int hp, int mp, int atk, int def)
        {
            this.name = name;
            this.hp = hp;
            this.mp = mp;
            this.atk = atk;
            this.def = def;
        }

        public void Print()
        {
            Console.WriteLine($"NAME : {name}\\n" +
                              $"HP : {hp}\\n" +
                              $"MP : {mp}\\n" +
                              $"ATK : {atk}\\n" +
                              $"DEF : {def}\\n");
        }

        public string Name
        { 
            get { return name; }
            set { name = value; }
        }

        public int Hp
        {
            get { return hp; }
            set { hp = value; }
        }

        public int Mp
        {
            get { return mp; }
            set { mp = value; }
        }

        public int Atk
        {
            get { return atk; }
            set { atk = value; }
        }
        
        public int Def
        {
            get { return def; }
            set { def = value; }
        }
    }

    class MainApp
    {
        static void Main(string[] args)
        {
            Type type = Type.GetType("NewCharacter.Profile");
            MethodInfo methodInfo = type.GetMethod("Print");
            PropertyInfo nameProperty = type.GetProperty("Name");
            PropertyInfo hpProperty = type.GetProperty("Hp");
            PropertyInfo mpProperty = type.GetProperty("Mp");
            PropertyInfo atkProperty = type.GetProperty("Atk");
            PropertyInfo defProperty = type.GetProperty("Def");

            object profile = Activator.CreateInstance(type, "용사");
            methodInfo.Invoke(profile, null);

            profile = Activator.CreateInstance(type);
            nameProperty.SetValue(profile, "치트 용사", null);
            hpProperty.SetValue(profile, 1000, null);
            mpProperty.SetValue(profile, 2000, null);
            atkProperty.SetValue(profile, 10000, null);
            defProperty.SetValue(profile, 20000, null);

            methodInfo.Invoke(profile, null);
        }
    }
}