C#/기술 개발

C# string(문자)에 따라 다른 class(클래스) 호출하기 (With Dictionary)

sheepone 2022. 4. 13. 14:53
반응형

1. 개요

Dictionary에 문자를 키로 사용하고 Value에 Delegate로 연결하여 함수를 넣어준다.

반환이 없으면 Action을 사용 반환값이 있으면 Func을 사용한다.

 

2. 코드

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WindowsFormsApp17
{
    public partial class Form1 : Form
    {
        Dictionary<string, Delegate> dic ;
        public Form1()
        {
            InitializeComponent();

            dic = new Dictionary<string, Delegate>(); 

            dic.Add(nameof(Test1),new Action<int>(Test1)); //in
            dic.Add(nameof(Test2),new Func  <int,string>(Test2)); //int, out

        }

        public void Test1(int _iNo)
        {
            listBox1.Items.Add("Test1 Arg : " + _iNo.ToString());
        }

        public string Test2(int _iNo)
        {
            listBox1.Items.Add("Test2 Arg : " + _iNo.ToString());
            return "Test2 Rst";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int iArg = int.Parse(textBox2.Text);
            var rst = dic[textBox1.Text].DynamicInvoke(iArg) ;

            if(rst != null)
                listBox1.Items.Add(rst.ToString());
        }

    }
}

 

Function으로 Test1과 Test2를 등록

 

3. 결과

Function에 Test1을 입력 인자에 111을 입력하고 CHECK 버튼을 눌럿을때

결과는 없고 Test1내부에서 리스트박스에 Test1 Arg : 111을 입력

(입력된 텍스트 Test1으로 Test1함수를 인자 111로 실행)

 

Function에 Test2를 입력 인자 222를 입력 CHECK 버튼을 눌렀을때

Test2함수내부에서 Test2 Arg:222 를 리스트박스에 입력 결과값으로 Test2 Rst를 받은 모습

(입력된 텍스트 Test2으로 Test2함수를 인자 111로 실행하고 결과값을 받아옴)

 

4. 예제소스

WindowsFormsApp17.zip
0.24MB

반응형