Language/C#

[C#] Func / Action / 익명 형식

마탁이 2020. 12. 26. 21:14

1. Func

 - 내부 처리 완료 후 반환되는 결과값이 있다.

 - 특정 조건으로 필터링하고 그 결과를 반환하는 Where 같은 메소드를 구현할 때 유용

 

2. Action

 - 내부 처리를 완료 후 반환되는 결과값이 없다.

 - 어떤 처리 진행을 보여주는 UI 업데이트 같은 처리를 할 때 유용

 

using System;
using System.Collections;
using System.Collections.Generic;

namespace TestPro
{

    class Program
    {
        private static List<int> FilterOfInts(int[] source, Func<int, bool> filter)
        {
            List<int> result = new List<int>();
            foreach (int i in source)
            {
                if (filter(i))
                {
                    result.Add(i);
                }
            }

            return result;
        }

        static void Main(string[] args)
        {
            int[] source = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            // 홀수 필터
            List<int> oddNums = FilterOfInts(source, i => ((i & 1) == 1));
            foreach (var item in oddNums)
            {
                Console.WriteLine(item);
            }

            // 짝수 필터
            List<int> evenNums = FilterOfInts(source, i => ((i & 1) == 0));
            foreach (var item in evenNums)
            {
                Console.WriteLine(item);
            }
        }
    }
}

 

3. 익명 형식

 - 메소드 내에서 즉시 데이터 구조를 정의하여 사용할 수 있도록 해준다.

 - 익명 형식을 사용하면 구조체를 미리 정의하는 것이 아닌 사용하고자 하는 시점에 바로 정의해서 사용 가능.

 - 익명 형식은 var 형식으로 선언되어야 한다.

 

using System;
using System.Collections;
using System.Collections.Generic;

namespace TestPro
{

    class Program
    {
        static void Main(string[] args)
        {
            var emp = new { birthDay = 2020, Name = "홍길동" };
            Console.WriteLine("emp name {0}, birth {1}", emp.Name, emp.birthDay);

            var emps = new[]
            {
                new {birthDay = 2020, Name = "일등이" },
                new {birthDay = 2020, Name = "이등이"}
            };
            foreach(var item in emps)
            {
                Console.WriteLine("emps name {0}, birth {1}", item.Name, item.birthDay);
            }
        }
    }
}