星期三, 8月 14, 2019

[C#] Delegate 各版本寫法

使用 Predicate、Func 來複習 Delegate 各版本用法
using System;
using System.Collections.Generic;

namespace DelegateSample
{
    class Program
    {
        static void Main(string[] args)
        {
            var data = GetDate();

            // 寫法 1:C# 1.0
            Predicate<Employee> d1 = new Predicate<Employee>(GetEmployee1);
            Employee e1 = data.Find(e => d1(e));
            Console.WriteLine(e1.ToString());

            // 寫法 2:C# 2.0
            Predicate<Employee> d2 = GetEmployee2;
            Employee e2 = data.Find(e => d2(e));
            Console.WriteLine(e2.ToString());

            // 寫法 3:C# 2.0 - 匿名方法
            Predicate<Employee> d3 = delegate (Employee e) { return e.EmployeeID == 3; }; // delegate 字樣可以省略
            Employee e3 = data.Find(d3);
            Console.WriteLine(e3.ToString());

            // C# 3.0 Lambda Expression
            // 寫法 4:
            Employee e4 = data.Find((Employee e) => e.EmployeeID == 4);
            Console.WriteLine(e4.ToString());
            
            // 寫法 5:實務上使用
            Employee e5 = data.Find(e => e.EmployeeID == 5);
            Console.WriteLine(e5.ToString());

            // 寫法 6:利用 Func 來練習
            Func<Employee, int, bool> d6 = new Func<Employee, int, bool>(GetEmployee);
            Employee e6 = data.Find(e => d6(e, 6));
            Console.WriteLine(e6.ToString());
        }

        private static List<Employee> GetDate()
        {
            return new List<Employee>()
            {
                new Employee(){ EmployeeID = 1 , EmployeeName = "Name1"} ,
                new Employee(){ EmployeeID = 2 , EmployeeName = "Name2"} ,
                new Employee(){ EmployeeID = 3 , EmployeeName = "Name3"} ,
                new Employee(){ EmployeeID = 4 , EmployeeName = "Name4"} ,
                new Employee(){ EmployeeID = 5 , EmployeeName = "Name5"} ,
                new Employee(){ EmployeeID = 6 , EmployeeName = "Name6"}
            };
        }

        private static bool GetEmployee1(Employee employee)
        {
            return GetEmployee(employee, 1);
        }

        private static bool GetEmployee2(Employee employee)
        {
            return GetEmployee(employee, 2);
        }

        private static bool GetEmployee(Employee employee, int targetEmployeeID)
        {
            return employee.EmployeeID == targetEmployeeID ? true : false;
        }
    }

    public class Employee
    {
        public int EmployeeID { get; set; }
        public string EmployeeName { get; set; }

        public override string ToString()
        {
            return $"{EmployeeID}-{EmployeeName}";
        }
    }
}
    延伸閱讀
  • [C#] Delegate 練習 12

沒有留言:

張貼留言