2020年5月30日 星期六

再論委派 AnonymousMethod及 Predicate

static void AnonymousMethodsSample()
        {
            List<Gamer> listGamers = new List<Gamer>
            {
                new Gamer{ Id = 1, Name = "Name01"},
                new Gamer{ Id = 2, Name = "Name02"},
                new Gamer{ Id = 3, Name = "Name03"},
                new Gamer{ Id = 4, Name = "Name04"}
            };
         
            Predicate<Gamer> predicateGetGamerId1 = new Predicate<Gamer>(GetGamerId1);
            Gamer gamerId1 = listGamers.Find(g => predicateGetGamerId1(g));
            Console.WriteLine($"predicateGetGamerId1 : gamerId1.Id=={gamerId1.Id}, gamerId1.Name=={gamerId1.Name}.");

            //
            Predicate<Gamer> predicateGetGamerId9= g => g.Id == 3;           
            Gamer gamerId9= listGamers.Find(predicateGetGamerId9);      
            Console.WriteLine($"predicateGetGamerId1 : gamerId1.Id=={gamerId9.Id}, gamerId1.Name=={gamerId9.Name}.");



            // "new Predicate<Gamer> " can be omitted.
            Predicate<Gamer> predicateGetGamerId2 = GetGamerId2;
            Gamer gamerId2 = listGamers.Find(g => predicateGetGamerId2(g));
            Console.WriteLine($"predicateGetGamerId2 : gamerId2.Id=={gamerId2.Id}, gamerId2.Name=={gamerId2.Name}.");

            // Anonymous method is being passed as an argument to
            // the Find() method. This anonymous method replaces
            // the need for Step 1, 2 and 3
            Gamer gamerId3 = listGamers.Find(delegate (Gamer g) { return g.Id == 3; });
            Console.WriteLine($"predicateGetGamerId3 : gamerId3.Id=={gamerId3.Id}, gamerId3.Name=={gamerId3.Name}.");

            //using lambda expression
            //=> is called lambda operator and read as GOES TO
            Gamer gamerId3V2 = listGamers.Find(g => g.Id == 3);
            Console.WriteLine($"predicateGetgamerId3V2 : gamerId3V2.Id=={gamerId3V2.Id}, gamerId3V2.Name=={gamerId3V2.Name}.");

            //using lambda expression
            Gamer gamerId3V3 = listGamers.Find((Gamer g) => g.Id == 3);
            Console.WriteLine($"predicateGetgamerId3V2 : gamerId3V3.Id=={gamerId3V3.Id}, gamerId3V3.Name=={gamerId3V3.Name}.");
        }

        // Step 1: Create a method whose signature matches Predicate<Gamer> delegate.
        private static bool GetGamerId1(Gamer g)
        {
            return g.Id == 1;
        }

        private static bool GetGamerId2(Gamer g)
        {
            return g.Id == 2;
        }

沒有留言:

張貼留言