C#/기술 개발

C# string(문자)에 따라 다른 class(클래스) 호출하기 (스크립트 언어)

sheepone 2021. 7. 12. 14:10
반응형
using Link;
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WindowsFormsApp43
{
    public partial class Form1 : Form
    {
        private static Dictionary<string, Type> s_functions = new Dictionary<string, Type>();

        public Form1()
        {
            InitializeComponent();

            Type type1 = Type.GetType("Link." + "Test1");
            Type type2 = Type.GetType("Link." + "Test2");

            //텍스트 박스 글짜에 따라 다른 클래스 등록
            s_functions.Add("textBox1",type1);
            s_functions.Add("textBox2",type2);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //텍스트 박스 글짜에 따라 다른 클래스 호출
            string skey = textBox1.Text;
            if (s_functions.ContainsKey(skey))
            {
                Type type = s_functions[skey];
                CFunction instance = Activator.CreateInstance(type) as CFunction;
                var print = instance.Print();
                richTextBox1.AppendText(print + "\r\n");
            }
        }
    }

}

namespace Link
{
    public abstract class CFunction
    {
        abstract public string Print ();
    }
    public class Test1 : CFunction
    {   
        override public string Print()
        {
            return "Class Test1";
        }
    }

    public class Test2 : CFunction
    {   
        override public string Print()
        {
            return "Class Test2";
        }
    }
}

 

실행 화면 1

textBox1이 입력되어 있을때는 Class Test1 수행.

 

실행 화면 2

textBox2이 입력되어 있을때는 Class Test2 수행.

반응형