성장일기

07/24 본문

프로그래밍언어/C#

07/24

김몽몽 2020. 7. 27. 10:20
using System;
public class Mathematics
{
    delegate int CalcDelegate(int x, int y);
    static int Add(int x, int y) { return x + y; }
    static int Sub(int x, int y) { return x - y; }
    static int Mul(int x, int y) { return x * y; }
    static int Div(int x, int y) { return x / y; }
    CalcDelegate[] methods;

    public Mathematics() // 생성자
    {
        methods = new CalcDelegate[] { Mathematics.Add, Mathematics.Sub, Mathematics.Mul, Mathematics.Div };
    }
    public void Calculate(char opCode, int operand1, int oprand2)
    {
        Console.Write(opCode + " : ");
        switch (opCode)
        {
            case '+':
                Console.WriteLine(methods[0](operand1, oprand2));
                break;
            case '-':
                Console.WriteLine(methods[1](operand1, oprand2));
                break;
            case '*':
                Console.WriteLine(methods[2](operand1, oprand2));
                break;
            case '/':
                Console.WriteLine(methods[3](operand1, oprand2));
                break;
        }
    }
    class Program
    {
        delegate void WorkDelegate(char arg1, int arg2, int arg3);
        static void Main(string[] args)
        {
            Mathematics mathematics = new Mathematics();
            WorkDelegate workDelegate = mathematics.Calculate;
            workDelegate('+', 10, 5);
            workDelegate('-', 10, 5);
            workDelegate('*', 10, 5);
            workDelegate('/', 10, 5);
        }
    }