2016년 4월 30일 토요일

[C#] Callback Func



예제 1

namespace Cshop_v6._0
{
    delegate int GetResultDelegate();

    class Target
    {
        public void Do(GetResultDelegate getResult)
        {
            Console.WriteLine(getResult()); // 콜백 메서드 호출
        }
    }

    class Source
    {
        public int GetResult() // 콜백 용도로 전달된 메서드
        {
            return 10;
        }

        public void Test()
        {
            Target target = new Target();
            target.Do(new GetResultDelegate(this.GetResult));
        }
    }
}

예제 2

namespace Cshop_v6._0
{
    delegate int GetResultDelegate(int x, int y);

    class Target
    {
        public void Do(GetResultDelegate getResult, int x, int y)
        {
            Console.WriteLine(getResult(x, y));
        }
    }

    class Source
    {
        public static int GetResult(int x, int y)
        {
            return x * y;
        }

        public static void Main()
        {
            Target target = new Target();
            GetResultDelegate gd = GetResult;
            target.Do(gd, 5, 10);
        }
    }
}

[C#] Delegate



접근제한자 delegate 대상_메서드_반환타입 식별자(… … 대상_메서드_매개변수_목록 … …);

예제 1

namespace Cshop_v6._0
{
    public class Mathematics
    {
        delegate int CalcDelegate(int x, int y);

        static int Add(int x, int y)      { return x + y; }
        static int Subtract(int x, int y) { return x - y; }
        static int Multiply(int x, int y) { return x * y; }
        static int Devide(int x, int y)   { return x / y; }

        CalcDelegate[] methods;

        public Mathematics()
        {
            methods = new CalcDelegate[] { Mathematics.Add, Mathematics.Subtract, Mathematics.Multiply, Mathematics.Devide };
        }

        public void Calculate(char opCode, int operand1, int operand2)
        {
            switch (opCode)
            {
                case '+': Console.WriteLine("+: " + methods[0](operand1, operand2)); break;
                case '-': Console.WriteLine("-: " + methods[1](operand1, operand2)); break;
                case '*': Console.WriteLine("*: " + methods[2](operand1, operand2)); break;
                case '/': Console.WriteLine("/: " + methods[3](operand1, operand2)); break;
            }
        }
    }

    class Program
    {
        delegate void WorkDelegate(char arg1, int arg2, int arg3);

        static void Main()
        {
            Mathematics math = new Mathematics();
            WorkDelegate work = math.Calculate;

            work('+', 10, 5);
            work('-', 10, 5);
            work('*', 10, 5);
            work('/', 10, 5);
        }
    }
}

예제 2

namespace Cshop_v6._0
{
    class Program
    {
        delegate void CalcDelegate(int x, int y);

        static void Add(int x, int y) { Console.WriteLine(x + y); }
        static void Subtract(int x, int y) { Console.WriteLine(x - y); }
        static void Multiply(int x, int y) { Console.WriteLine(x * y); }
        static void Divide(int x, int y) { Console.WriteLine(x / y); }

        static void Main()
        {
            CalcDelegate calc = Add;
            calc += Subtract;
            calc += Multiply;
            calc += Divide;

            calc(10, 5);

            // 출력결과
            /*
            15
            5
            50
            2
            */

            Console.WriteLine("=================================================================");

            calc -= Divide;

            calc(10, 5);


            // 출력결과
            /*
            15
            5
            50
            */
        }
    }
}

2016년 4월 22일 금요일

[C#] Lambda expression-1



코드로서의 람다식

class Program
{
    delegate int? MyDivide(int a, int b);
    static void Main(string[] args)
    {
        MyDivide myFunc = (a, b) =>
        {
            if (b == 0)
            {
                return null;
            }
            return a / b;
        };
        Console.WriteLine("10 / 0 = " + myFunc(10, 0));
     }
}

Func, Action 델리게이트를 이용한 Lambda expression

// public delegate void Action(T obj);
// 반환값이 없는 델리게이트로서 T 형식 매개변수는 입력될 인자 1개의 타입을 지정

// public delegate TResult Func();
// 반환값이 있는 델리게이트로서 TResult 형식 매개변수는 반환될 타입을 지정

class Program
{
    static void Main()
    {
        Action log = (text) =>
        {
            Console.WriteLine(text);
        };

        log("Hello world!");

        Func age = (a, b) => a + b;

        Console.WriteLine(age(14, 14));
    }
}

/*
public delegate void Action(T arg);
public delegate void Action(T1 arg1, T2 arg2);
...
T1~T16까지 Action delegate 정의

public delegate TResult Func();
public delegate TResult Func(T arg);
public delegate TResult Func(T1 arg1, T2 arg2);
...
T1 ~ T16까지 Func delegate 정의
*/

Collection & Lambda expression [ForEach]

// List에 정의된 ForEach
// public void ForEach(Action action);

// Array에 정의된 ForEach
// public static void ForEach(T [] array, Action action);
class Program
{
    static void Main()
    {
        List list = new List { 1, 2, 3, 10, 100 };

        // 일반형식
        foreach(var item in list)
        {
            Console.WriteLine(item + " * 2 == " + (item * 2));
        }

        // 람다식
        list.ForEach((elem) => { Console.WriteLine(elem + " * 2 == " + (elem * 2)); });
        // 또는
        Array.ForEach(list.ToArray(), (elem) => { Console.WriteLine(elem + " * 2 == " + (elem * 2)); });
    }
}

Collection & Lambda expression [FindAll, Where, Count, Select]

class Program
{
    static void Main()
    {

        List list = new List { 1, 2, 3, 10, 100, 501 };

        // 짝수로 구성된 리스트 반환
        List result = new List();

        // 일반형식
        foreach (var item in list)
        {
            if (item % 2 == 0)
            {
                result.Add(item);
            }
        }
        
        // FindAll
        result = list.FindAll((elem) => elem % 2 == 0);
 
        // Where
        IEnumerable enumList = list.Where((elem) => elem % 2 == 0);

        // Count
        int count = list.Count((elem) => elem > 3);

        // Select
        IEnumerable doubleList = list.Select((elem) => (double)elem);
        IEnumerable personList = list.Select((elem) => new Person {Age = elem, Name = Guid.NewGuid().ToString()});
        var itemList = list.Select((elem) => new {TypeNo = elem, CreateDate = DateTime.Now});
    }
}
class Person
{
    public int Age {get; set;}
    public string Name {get; set;}
}