Exemplo n.º 1
0
        static void Main(string[] args)
        {
            /*
             * W rozdziale 14. pisaliśmy, że słowo kluczowe var pozwala IDE określić typ
             * obiektu podczas kompilacji.
             *
             * Używając var i new, można także tworzyć obiekty o anonimowych typach.
             *
             * Więcej informacji na temat tych typów możesz znaleźć na stronie
             * http://msdn.microsoft.com/pl-pl/library/bb397696.aspx.
             */

            // Tworzymy typ anonimowy przypominający klasę Guy.
            var anonymousGuy = new { Name = "Bartek", Age = 43, Cash = 137 };

            // Kiedy będziesz wpisywał poniższą instrukcję, IntelliSense wyświetli
            // składowe - Name, Age oraz Cash.
            Console.WriteLine("{0} ma {1} lata i {2} zł gotówki.",
                              anonymousGuy.Name, anonymousGuy.Age, anonymousGuy.Cash);
            // Wyniki: Bartek ma 43 lata i 137 zł gotówki.

            // Instancja typu anonimowego ma także całkiem sensowną metodę ToString().
            Console.WriteLine(anonymousGuy.ToString());
            // Wyniki: { Name = Bartek, Age = 43, Cash = 137 }

            /*
             * W rozdziale 15. dowiedziałeś się, jak używać delegatów, by tworzyć
             * referencje do metod. We wszystkich przedstawionych przykładach ich
             * zastosowania przypisywaliśmy do nich istniejące metody.
             *
             * Metody anonimowe to metody deklarowane w instrukcji - używane są przy
             * tym nawiasy klamrowe { } podobnie jak w przypadku anonimowych typów.
             *
             * Więcej informacji na temat anonimowych metod znajdziesz na stronie
             * http://msdn.microsoft.com/pl-pl/library/0yw3tz5k.aspx.
             */

            // Oto metoda anonimowa, która wyświetla na konsoli liczbę i łańcuch znaków.
            // Jej deklaracja pasuje do delegata MyIntAndString (zdefiniowanego
            // wcześniej), zatem możemy ją przypisać do zmiennej typu MyIntAndString.
            MyIntAndString printThem = delegate(int i, string s)
            { Console.WriteLine("{0} - {1}", i, s); };

            printThem(123, "cztery pięć sześć");
            // Wyniki: 123 - cztery pięć sześć

            // A tu mamy kolejną anonimową metodę o takiej samej sygnaturze (int,
            // string). Ta metoda sprawdza, czy w łańcuchu występuje liczba.
            MyIntAndString contains = delegate(int i, string s)
            { Console.WriteLine(s.Contains(i.ToString())); };

            contains(123, "cztery pięć sześć");
            // Wynik: False

            contains(123, "cztery 123 pięć sześć");
            // Wynik: True

            // Można dynamicznie wywołać metodę, używając Delegate.DynamicInvoke()
            // i przekazując parametry wywołania w formie tablicy obiektów.
            Delegate d = contains;

            d.DynamicInvoke(new object[] { 123, "cztery 123 pięć sześć" });
            // Output: True

            /*
             * Wyrażenia lambda są specjalnym rodzajem anonimowych metod, które
             * korzystają z operatora =>. Nosi on nazwę operatora lambda, jednak
             * w przypadku tych wyrażeń, czytając go, zazwyczaj używamy
             * określenia "przechodzi do". Oto proste wyrażenie lambda:
             *
             * (a, b) => { return a + b; }
             *
             * Można je przeczytać jako "a i b przechodzi do a plus b" - jest to
             * metoda anonimowa dodająca dwie wartości. Można wyobrażać sobie wyrażenia
             * lambda jako metody anonimowe pobierające parametry i zwracające wartości.
             *
             * Więcej informacji na temat wyrażeń lambda znajdziesz na stronie
             * http://msdn.microsoft.com/pl-pl/library/bb397687.aspx.
             */

            // Oto wyrażenie lambda służące do dodawania dwóch liczb. Jego sygnatura
            // odpowiada delegatowi CombineTwoInts, a zatem możesz je przypisać do
            // zmiennej typu CombineTwoInts. Zwróć uwagę, że delegat ten zwraca
            // wartość typu int, zatem także wyrażenie lambda musi taką zwracać.
            CombineTwoInts adder = (a, b) => { return(a + b); };

            Console.WriteLine(adder(3, 5));
            // Wyniki: 8

            // A oto kolejne wyrażenie lambda - to z kolei mnoży dwie liczby:
            CombineTwoInts multiplier = (int a, int b) => { return(a * b); };

            Console.WriteLine(multiplier(3, 5));
            // Wyniki: 15

            // Łącząc wyrażenia lambda z LINQ, można wykonywać naprawdę złożone
            // operacje. Poniżej przedstawiliśmy prosty przykład.
            var greaterThan3 = new List <int> {
                1, 2, 3, 4, 5, 6
            }.Where(x => x > 3);

            foreach (int i in greaterThan3)
            {
                Console.Write("{0} ", i);
            }
            // Wyniki: 4 5 6

            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            //NO LAMBDA- no anonomus method- NAMED method
            int Sum(int x, int y)
            {
                return(x + y);
            }

            //przypisanie- dwie metody do wywołania
            //MyDelegate d = new MyDelegate(Sum);
            MyDelegate deletaTeSum = Sum;

            int result1 = deletaTeSum.Invoke(12, 15);

            Console.WriteLine("result 1:  " + result1);

            int result2 = deletaTeSum(12, 15);

            Console.WriteLine("result 2:  " + result2);


            void Execute()
            {
                //NO LAMBDA- anonomous method
                MultiplyNumbers multiply = delegate(int number1, int number2)
                {
                    return(number1 * number2);
                };

                //wykonanie
                Console.WriteLine("Anonomous method result- Execute:  " + multiply(4, 3) + "  " + multiply(4, 3).GetType());
            }

            Execute();

            //delegate, anonymous method using lambda, dynamic invoke (slow)
            MyIntAndString lambda = (int a, string b) => { Console.WriteLine("ELO: " + a + b); };

            //parameter is array of objects
            lambda.DynamicInvoke(new object[] { 123, "four five six" });


            //LAMBDA DELEGATES
            //  => GOES TO
            CombineTwoInts adder = (a, b) => { return(a + b); };

            Console.WriteLine("lambda delegate:  " + adder(3, 5));

            //LAMBDA DELEGATE
            CombineTwoInts multiplier = (int a, int b) => { return(a * b); };

            Console.WriteLine("lambda delegate2:  " + multiplier(3, 5));



            //LAMBDA PREDICATE
            var greaterThan3 = new List <int> {
                1, 2, 3, 4, 5, 6
            }.Where(x => x > 3);

            foreach (int i in greaterThan3)
            {
                Console.Write("Lambda in anonomoush method: " + i + ", ");
            }



            //Mosh lambda DELEGATE
            Func <int, int> square = number => number * number;

            Console.WriteLine(square(5));

            Console.ReadKey();
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            // Anonymous Type
            // Create an anonymous type that looks a lot like a guy:
            var anonymousGuy = new { Name = "Bob", Age = 43, Cash = 137 };

            Console.WriteLine("{0} is {1} years old and has {2} bucks.",
                              anonymousGuy.Name, anonymousGuy.Age, anonymousGuy.Cash);
            Console.WriteLine();
            Console.WriteLine(anonymousGuy.ToString());

            Console.WriteLine();

            // Anonymous Method
            // Here's an anonymous method that writes an int and a string to the console.
            // Its declaration matches our MyIntAndString delegate (defined above), so
            //      we can assign it to a variable of type MyIntAndString.
            MyIntAndString printThem = delegate(int i, string s)
            { Console.WriteLine("{0} - {1}", i, s); };

            printThem(123, "four five six");
            Console.WriteLine();

            MyIntAndString contains = delegate(int i, string s)
            { Console.WriteLine(s.Contains(i.ToString())); };

            // False
            contains(123, "four five six");
            Console.WriteLine();

            // True
            contains(123, "four 123 five six");
            Console.WriteLine();

            // You can dynamically invoke a method using Delegate.DynamicInvoke(),
            //      passing the parameters to the method as an array of objects.
            Delegate d = contains;

            // True
            d.DynamicInvoke(new object[] { 123, "four 123 five six" });
            Console.WriteLine();

            // Lambda Expressions
            // (a,b) => {return a + b; }
            // Reads as "a and b goes to a plus b"

            CombineTwoInts adder = (a, b) => { return(a + b); };

            Console.WriteLine(adder(3, 5));
            Console.WriteLine();

            CombineTwoInts multiplier = (int a, int b) => { return(a * b); };

            Console.WriteLine(multiplier(3, 5));
            Console.WriteLine();

            // Lambda expression combined with LINQ
            var greaterThan3 = new List <int> {
                1, 2, 3, 4, 5, 6
            }.Where(x => x > 3);

            foreach (int i in greaterThan3)
            {
                Console.WriteLine("{0} ", i);
            }
            Console.WriteLine();

            // Another lambda expression using a non-anonymous type
            List <int> newList = new List <int>()
            {
                1, 2, 3, 4, 5, 6
            };
            var lessThan3 = newList.Where(x => x < 3);

            foreach (int i in lessThan3)
            {
                Console.WriteLine("{0} ", i);
            }
            Console.WriteLine();

            Console.ReadKey();
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            /*
             * In Chapter 15, you saw how the var keyword let the IDE determine the
             * type of an object at compile time.
             *
             * You can also create objects with anonymous types using var and new.
             *
             * You can learn more about anonymous types here:
             * http://msdn.microsoft.com/en-us/library/bb397696.aspx
             */
            // Create an anonymous type that looks a lot like a guy:
            var anonymousGuy = new { Name = "Bob", Age = 43, Cash = 137 };

            // When you type this in, the IDE’s IntelliSense automatically picks up
            // the members -- Name, Age and Cash show up in the IntelliSense window.
            Console.WriteLine("{0} is {1} years old and has {2} bucks",
                              anonymousGuy.Name, anonymousGuy.Age, anonymousGuy.Cash);
            // Output: Bob is 43 years old and has 137 bucks
            // An instance of an anonymous type has a sensible ToString() method.
            Console.WriteLine(anonymousGuy.ToString());
            // Output: { Name = Bob, Age = 43, Cash = 137 }

            /*
             * In Chapter 11, you learned about how you can use a delegate to reference
             * a method. In all of the examples of delegates that you’ve seen so far,
             * you assigned an existing method to a delegate.
             *
             * Anonymous methods are methods that you declare in a statement -- you
             * declare them using curly brackets { }, just like with anonymous types.
             *
             * You can learn more about anonymous methods here:
             * http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx
             */

            // Here’s an anonymous method that writes an int and a string to the console.
            // Its declaration matches our MyIntAndString delegate (defined above), so
            // we can assign it to a variable of type MyIntAndString.
            MyIntAndString printThem = delegate(int i, string s)
            { Console.WriteLine("{0} - {1}", i, s); };

            printThem(123, "four five six");
            // Output: 123 - four five six
            // Here’s another anonymous method with the same signature (int, string).
            // This one checks if the string contains the int.
            MyIntAndString contains = delegate(int i, string s)
            { Console.WriteLine(s.Contains(i.ToString())); };

            contains(123, "four five six");
            // Output: False
            contains(123, "four 123 five six");
            // Output: True
            // You can dynamically invoke a method using Delegate.DynamicInvoke(),
            // passing the parameters to the method as an array of objects.
            Delegate d = contains;

            d.DynamicInvoke(new object[] { 123, "four 123 five six" });
            // Output: True

            /*
             * A lambda expression is a special kind of anonymous method that uses
             * the => operator. It’s called the lambda operator, but when you’re
             * talking about lambda expressions you usually say "goes to" when
             * you read it. Here’s a simple lambda expression:
             *
             * (a, b) => { return a + b; }
             *
             * You could read that as "a and b goes to a plus b" -- it’s an anonymous
             * method for adding two values. You can think of lambda expressions as
             * anonymous methods that take parameters and can return values.
             *
             * You can learn more about lambda expressions here:
             * http://msdn.microsoft.com/en-us/library/bb397687.aspx
             */
            // Here’s that lambda expression for adding two numbers. Its signature
            // matches our CombineTwoInts delegate, so we can assign it to a delegate
            // variable of type CombineTwoInts. Notice how CombineTwoInts’s return
            // type is int -- that means the lambda expression needs to return an int.
            CombineTwoInts adder = (a, b) => { return(a + b); };

            Console.WriteLine(adder(3, 5));
            // Output: 8
            // Here’s another lambda expression -- this one multiplies two numbers.
            CombineTwoInts multiplier = (int a, int b) => { return(a * b); };

            Console.WriteLine(multiplier(3, 5));
            // Output: 15
            // You can do some seriously powerful stuff when you combine lambda
            // expressions with LINQ. Here’s a really simple example:
            var greaterThan3 = new List <int> {
                1, 2, 3, 4, 5, 6
            }.Where(x => x > 3);

            foreach (int i in greaterThan3)
            {
                Console.Write("{0} ", i);
            }
            // Output: 4 5 6
            Console.ReadKey();
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            // Create an anonymous type that looks a lot like a guy:
            var anonymousGuy = new { Name = "Bob", Age = 43, Cash = 137 };

            // When you type this in, the IDE's IntelliSense automatically picks up
            // the members -- Name, Age and Cash show up in the IntelliSense window.
            Console.WriteLine("{0} is {1} years old and has {2} bucks",
                              anonymousGuy.Name, anonymousGuy.Age, anonymousGuy.Cash);
            // Output: Bob is 43 years old and has 137 bucks
            // An instance of an anonymous type has a sensible ToString() method.
            Console.WriteLine(anonymousGuy.ToString());
            // Output: { Name = Bob, Age = 43, Cash = 137 }
            // Here's an anonymous method that writes an int and a string to the console.
            // Its declaration matches our MyIntAndString delegate (defined above), so
            // we can assign it to a variable of type MyIntAndString.
            MyIntAndString printThem = delegate(int i, string s)
            { Console.WriteLine("{0} - {1}", i, s); };

            printThem(123, "four five six");
            // Output: 123 - four five six
            // Here's another anonymous method with the same signature (int, string).
            // This one checks if the string contains the int.
            MyIntAndString contains = delegate(int i, string s)
            { Console.WriteLine(s.Contains(i.ToString())); };

            contains(123, "four five six");
            // Output: False
            contains(123, "four 123 five six");
            // Output: True
            // You can dynamically invoke a method using Delegate.DynamicInvoke(),
            // passing the parameters to the method as an array of objects.
            Delegate d = contains;

            d.DynamicInvoke(new object[] { 123, "four 123 five six" });
            // Output: True
            // Here's that lambda expression for adding two numbers. Its signature
            // matches our CombineTwoInts delegate, so we can assign it to a delegate
            // variable of type CombineTwoInts. Notice how CombineTwoInts's return
            // type is int -- that means the lambda expression needs to return an int.
            CombineTwoInts adder = (a, b) => { return(a + b); };

            Console.WriteLine(adder(3, 5));
            // Output: 8
            // Here's another lambda expression -- this one multiplies two numbers.
            CombineTwoInts multiplier = (int a, int b) => { return(a * b); };

            Console.WriteLine(multiplier(3, 5));
            // Output: 15
            // You can do some seriously powerful stuff when you combine lambda
            // expressions with LINQ. Here's a really simple example:
            var greaterThan3 = new List <int> {
                1, 2, 3, 4, 5, 6
            }.Where(x => x > 3);

            foreach (int i in greaterThan3)
            {
                Console.Write("{0} ", i);
            }
            // Output: 4 5 6
#if DEBUG
            Console.ReadKey();
#endif
        }