Przejdź do treści stopki
Iron Academy Logo
Naucz się C#
Naucz się C#

Inne Kategorie

Zrozumienie delegatów w C#

Tim Corey
1h 9m 11s

Delegaty w C# to potężna cecha, a jednak wielu programistów nie jest zaznajomionych z ich efektywnym użyciem. Film Tima Coreya o "Delegaty w C# - praktyczna demonstracja, w tym Action i Func" dostarcza dokładnego wyjaśnienia, czym są delegaty, jak ich używać i dłączego są użyteczne.

Ten artykuł dostarczy ci eksperckich spostrzeżeń Tima na temat delegatów w C#, oferując jasne wyjaśnienie ich użycia i praktycznych zastosowań. Nauczysz się, jak delegaty mogą zwiększyć elastyczność i wydajność twojego kodu, z przykładami użycia w systemie koszyka zakupowego.

Wprowadzenie

Tim wprowadza pojęcie delegatów, podkreślając ich moc i wszechstronność w C#. Zapewnia widzów, że pomimo niektórych przerażających terminologii, podstawa delegatów jest prosta. Tim dąży do demistyfikacji delegatów i omawia specjalne typy, takie jak func i action.

Demonstracja aplikacji - przewodnik

Tim tworzy aplikację demo, aby zilustrować użycie delegatów. Rozwiązanie zawiera trzy projekty: Konsolowe UI, Bibliotekę Demo i WinForm UI. Początkowo skupienie się jest na Konsolowym UI i Bibliotece Demo.

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

namespace ConsoleUI
{
    class Program
    {
        static ShoppingCartModel cart = new ShoppingCartModel();

        static void Main(string[] args)
        {
            PopulateCartWithDemoData();

            Console.WriteLine($"The total for the cart is {cart.GenerateTotal():C2}");

            Console.ReadLine();
        }

        private static void PopulateCartWithDemoData()
        {
            cart.Items.Add(new ProductModel { ItemName = "Cereal", Price = 3.63M });
            cart.Items.Add(new ProductModel { ItemName = "Milk", Price = 2.95M });
            cart.Items.Add(new ProductModel { ItemName = "Strawberries", Price = 7.51M });
            cart.Items.Add(new ProductModel { ItemName = "Blueberries", Price = 6.75M });
        }
    }
}

public class ShoppingCartModel
{
    public List<ProductModel> Items { get; set; } = new List<ProductModel>();

    public decimal GenerateTotal()
    {
        decimal subtotal = Items.Sum(x => x.Price);

        if (subtotal > 100)
        {
            return subtotal * 0.80M;
        }
        else if (subtotal > 50)
        {
            return subtotal * 0.85M;
        }
        else if (subtotal > 10)
        {
            return subtotal * 0.90M;
        }
        else
        {
            return subtotal;
        }
    }
}

public class ProductModel
{
    public string ItemName { get; set; }
    public decimal Price { get; set; }
}
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleUI
{
    class Program
    {
        static ShoppingCartModel cart = new ShoppingCartModel();

        static void Main(string[] args)
        {
            PopulateCartWithDemoData();

            Console.WriteLine($"The total for the cart is {cart.GenerateTotal():C2}");

            Console.ReadLine();
        }

        private static void PopulateCartWithDemoData()
        {
            cart.Items.Add(new ProductModel { ItemName = "Cereal", Price = 3.63M });
            cart.Items.Add(new ProductModel { ItemName = "Milk", Price = 2.95M });
            cart.Items.Add(new ProductModel { ItemName = "Strawberries", Price = 7.51M });
            cart.Items.Add(new ProductModel { ItemName = "Blueberries", Price = 6.75M });
        }
    }
}

public class ShoppingCartModel
{
    public List<ProductModel> Items { get; set; } = new List<ProductModel>();

    public decimal GenerateTotal()
    {
        decimal subtotal = Items.Sum(x => x.Price);

        if (subtotal > 100)
        {
            return subtotal * 0.80M;
        }
        else if (subtotal > 50)
        {
            return subtotal * 0.85M;
        }
        else if (subtotal > 10)
        {
            return subtotal * 0.90M;
        }
        else
        {
            return subtotal;
        }
    }
}

public class ProductModel
{
    public string ItemName { get; set; }
    public decimal Price { get; set; }
}

Tim wyjaśnia strukturę i funkcjonalność aplikacji demo:

  • Model Koszyka Zakupowego: Reprezentuje koszyk zakupowy z listą przedmiotów (ProductModel) i oblicza całkowity koszt z rabatami na podstawie sumy częściowej.

  • Model Produktu: Reprezentuje pojedyncze przedmioty z nazwą i ceną jako właściwościami.

  • Aplikacja Konsolowa: Wypełnia koszyk danymi demo, oblicza całkowitą wartość i wyświetla ją.

Zrozumienie Rabatów

Tim przechodzi przez logikę rabatów w metodzie GenerateTotal, wyjaśniając, jak suma częściowa determinuje zastosowany rabat:

  • 20% rabatu dla sum częściowych powyżej 100 $.
  • 15% rabatu dla sum częściowych powyżej 50 $.
  • 10% rabatu dla sum częściowych powyżej 10 $.
  • Brak rabatu dla sum częściowych 10 $ lub mniejszych.

Tim używa punktu kontrolnego, aby pokazać logikę obliczeń i rabatów, zapewniając zrozumieniuiuiuiuie podstaw przed wprowadzeniem delegatów.

Wyjaśnianie i Tworzenie Delegatu

W tej sekcji Tim Corey zagłębia się w koncepcję delegatów w C#, wyjaśniając, jak działają i pokazując ich użycie na praktycznych przykładach kodu.

Czym jest Delegat?

Tim wyjaśnia, że delegat to zasadniczo sposób na przekazywanie metod jako parametrów. Zamiast przekazywać zmienną lub właściwość, przekazujesz metodę, co pozwala na bardziej elastyczny i wielokrotnego użytku kod.

Tworzenie i Użycie Delegata

Oto jak Tim prezentuje proces tworzenia i użycia delegata:

  1. Zdefiniuj Delegat:
  • Delegat jest definiowany na początku klasy, określając typ zwracany i typy parametrów.

    public delegate void MentionDiscount(decimal subtotal);
    public delegate void MentionDiscount(decimal subtotal);
    • Ten delegat określa metodę, która zwraca void i przyjmuje decimal jako parametr.
  1. Użycie Delegata w Metodzie:
  • Delegat jest używany jako parametr w metodzie GenerateTotal klasy ShoppingCartModel.

    public decimal GenerateTotal(MentionDiscount mentionDiscount)
    {
        decimal subtotal = Items.Sum(x => x.Price);
    
        // Call a method passed as a delegate
        mentionDiscount(subtotal);
    
        if (subtotal > 100)
        {
            return subtotal * 0.80M;
        }
        else if (subtotal > 50)
        {
            return subtotal * 0.85M;
        }
        else if (subtotal > 10)
        {
            return subtotal * 0.90M;
        }
        else
        {
            return subtotal;
        }
    }
    public decimal GenerateTotal(MentionDiscount mentionDiscount)
    {
        decimal subtotal = Items.Sum(x => x.Price);
    
        // Call a method passed as a delegate
        mentionDiscount(subtotal);
    
        if (subtotal > 100)
        {
            return subtotal * 0.80M;
        }
        else if (subtotal > 50)
        {
            return subtotal * 0.85M;
        }
        else if (subtotal > 10)
        {
            return subtotal * 0.90M;
        }
        else
        {
            return subtotal;
        }
    }
  1. Tworzenie Metody do Przekazania Delegatowi:
  • Metoda pasująca do podpisu delegata jest tworzona w klasie Program.

    private static void SubtotalAlert(decimal subtotal)
    {
        Console.WriteLine($"The subtotal is {subtotal:C2}");
    }
    private static void SubtotalAlert(decimal subtotal)
    {
        Console.WriteLine($"The subtotal is {subtotal:C2}");
    }
  1. Wywoływanie Metody GenerateTotal:
  • Metoda jest przekazywana do metody GenerateTotal za pomocą delegata.

    class Program
    {
        static ShoppingCartModel cart = new ShoppingCartModel();
    
        static void Main(string[] args)
        {
            PopulateCartWithDemoData();
    
            Console.WriteLine($"The total for the cart is {cart.GenerateTotal(SubtotalAlert):C2}");
    
            Console.ReadLine();
        }
    
        private static void PopulateCartWithDemoData()
        {
            cart.Items.Add(new ProductModel { ItemName = "Cereal", Price = 3.63M });
            cart.Items.Add(new ProductModel { ItemName = "Milk", Price = 2.95M });
            cart.Items.Add(new ProductModel { ItemName = "Strawberries", Price = 7.51M });
            cart.Items.Add(new ProductModel { ItemName = "Blueberries", Price = 6.75M });
        }
    }
    class Program
    {
        static ShoppingCartModel cart = new ShoppingCartModel();
    
        static void Main(string[] args)
        {
            PopulateCartWithDemoData();
    
            Console.WriteLine($"The total for the cart is {cart.GenerateTotal(SubtotalAlert):C2}");
    
            Console.ReadLine();
        }
    
        private static void PopulateCartWithDemoData()
        {
            cart.Items.Add(new ProductModel { ItemName = "Cereal", Price = 3.63M });
            cart.Items.Add(new ProductModel { ItemName = "Milk", Price = 2.95M });
            cart.Items.Add(new ProductModel { ItemName = "Strawberries", Price = 7.51M });
            cart.Items.Add(new ProductModel { ItemName = "Blueberries", Price = 6.75M });
        }
    }

Uruchamianie aplikacji

Tim uruchamia aplikację, aby pokazać, jak działa delegat. Output konsoli pokazuje sumę częściową i całkowitą dla koszyka, wskazując, że metoda SubtotalAlert została pomyślnie przekazana i wykonana za pomocą delegata.

Understanding Csharp Delegate 1 related to Uruchamianie aplikacji

Func i Action: Problemy, które możesz rozwiązać za pomocą delegatów

Tim Corey następnie bada użycie func i action delegatów w C#. Są to specjalne typy delegatów dostarczone przez Microsoft, aby uprościć użycie delegatów z generykami.

Identyfikacja Problemu

Tim podkreśla powszechny problem: zaszyta na stałe logika rabatów w metodzie GenerateTotal. To podejście jest nieelastyczne i wymaga zmian w kodzie, rekompilacji i ponownego wdrożenia za każdym razem, gdy zmieniają się zasady rabatów.

public decimal GenerateTotal()
{
    decimal subtotal = Items.Sum(x => x.Price);
    if (subtotal > 100)
    {
        return subtotal * 0.80M;
    }
    else if (subtotal > 50)
    {
        return subtotal * 0.85M;
    }
    else if (subtotal > 10)
    {
        return subtotal * 0.90M;
    }
    else
    {
        return subtotal;
    }
}
public decimal GenerateTotal()
{
    decimal subtotal = Items.Sum(x => x.Price);
    if (subtotal > 100)
    {
        return subtotal * 0.80M;
    }
    else if (subtotal > 50)
    {
        return subtotal * 0.85M;
    }
    else if (subtotal > 10)
    {
        return subtotal * 0.90M;
    }
    else
    {
        return subtotal;
    }
}

Wprowadzenie Delegata Func

Tim wprowadza delegata func, aby rozwiązać problem zaszytej na stałe logiki rabatów. Delegat func to generyczny delegat, który reprezentuje podpis metody z typem zwracanym i do 16 parametrami wejściowymi.

  1. Definiowanie Delegata Func:
  • Delegat func jest używany w metodzie GenerateTotal, aby dynamicznie obsługiwać obliczenia rabatów.

    public decimal GenerateTotal(Func<List<ProductModel>, decimal, decimal> calculateDiscountedTotal)
    {
        decimal subtotal = Items.Sum(x => x.Price);
        MentionDiscount(subtotal);
    
        return calculateDiscountedTotal(Items, subtotal);
    }
    public decimal GenerateTotal(Func<List<ProductModel>, decimal, decimal> calculateDiscountedTotal)
    {
        decimal subtotal = Items.Sum(x => x.Price);
        MentionDiscount(subtotal);
    
        return calculateDiscountedTotal(Items, subtotal);
    }
  1. Tworzenie Metody Obliczania Rabatów:
  • Metoda pasująca do podpisu delegata func jest tworzona w klasie Program.

    private static decimal CalculateLevelDiscount(List<ProductModel> items, decimal subtotal)
    {
        if (subtotal > 100)
        {
            return subtotal * 0.80M;
        }
        else if (subtotal > 50)
        {
            return subtotal * 0.85M;
        }
        else if (subtotal > 10)
        {
            return subtotal * 0.90M;
        }
        else
        {
            return subtotal;
        }
    }
    private static decimal CalculateLevelDiscount(List<ProductModel> items, decimal subtotal)
    {
        if (subtotal > 100)
        {
            return subtotal * 0.80M;
        }
        else if (subtotal > 50)
        {
            return subtotal * 0.85M;
        }
        else if (subtotal > 10)
        {
            return subtotal * 0.90M;
        }
        else
        {
            return subtotal;
        }
    }
  1. Przekazanie Metody do Delegata Func:
  • Metoda CalculateLevelDiscount jest przekazywana do metody GenerateTotal za pomocą delegata func.

    class Program
    {
        static ShoppingCartModel cart = new ShoppingCartModel();
    
        static void Main(string[] args)
        {
            PopulateCartWithDemoData();
    
            Console.WriteLine($"The total for the cart is {cart.GenerateTotal(CalculateLevelDiscount):C2}");
    
            Console.ReadLine();
        }
    
        private static void PopulateCartWithDemoData()
        {
            cart.Items.Add(new ProductModel { ItemName = "Cereal", Price = 3.63M });
            cart.Items.Add(new ProductModel { ItemName = "Milk", Price = 2.95M });
            cart.Items.Add(new ProductModel { ItemName = "Strawberries", Price = 7.51M });
            cart.Items.Add(new ProductModel { ItemName = "Blueberries", Price = 6.75M });
        }
    
        private static decimal CalculateLevelDiscount(List<ProductModel> items, decimal subtotal)
        {
            if (subtotal > 100)
            {
                return subtotal * 0.80M;
            }
            else if (subtotal > 50)
            {
                return subtotal * 0.85M;
            }
            else if (subtotal > 10)
            {
                return subtotal * 0.90M;
            }
            else
            {
                return subtotal;
            }
        }
    }
    class Program
    {
        static ShoppingCartModel cart = new ShoppingCartModel();
    
        static void Main(string[] args)
        {
            PopulateCartWithDemoData();
    
            Console.WriteLine($"The total for the cart is {cart.GenerateTotal(CalculateLevelDiscount):C2}");
    
            Console.ReadLine();
        }
    
        private static void PopulateCartWithDemoData()
        {
            cart.Items.Add(new ProductModel { ItemName = "Cereal", Price = 3.63M });
            cart.Items.Add(new ProductModel { ItemName = "Milk", Price = 2.95M });
            cart.Items.Add(new ProductModel { ItemName = "Strawberries", Price = 7.51M });
            cart.Items.Add(new ProductModel { ItemName = "Blueberries", Price = 6.75M });
        }
    
        private static decimal CalculateLevelDiscount(List<ProductModel> items, decimal subtotal)
        {
            if (subtotal > 100)
            {
                return subtotal * 0.80M;
            }
            else if (subtotal > 50)
            {
                return subtotal * 0.85M;
            }
            else if (subtotal > 10)
            {
                return subtotal * 0.90M;
            }
            else
            {
                return subtotal;
            }
        }
    }

Uruchamianie aplikacji

Tim demonstruje zmodyfikowaną aplikację, pokazując, że działa poprawnie i dynamicznie oblicza rabat na podstawie dostarczonej logiki.

Understanding Csharp Delegate 2 related to Uruchamianie aplikacji

Różnice między Delegatem a Func

Tim porównuje delegat niestandardowy i delegat func:

  • Delegat: Wymaga wyraźnego zdefiniowania podpisu, co zapewnia jasną dokumentację i strukturę.

  • Func: Bardziej zwięzły, ale wymaga każdorazowego określenia typów wejściowych i wyjściowych, co może być mniej jasne.

Oba podejścia oferują elastyczność, ale wybór zależy od konkretnego przypadku użycia i złożoności aplikacji.

Dłączego używać Delegatów, jeśli cała praca jest wykonywana gdzie indziej?

Tim Corey porusza powszechne pytanie dotyczące użycia delegatów: Dłączego mieć delegat, jeśli cała praca wydaje się być gdzie indziej?

Tim wyjaśnia, że celem delegatów jest zapewnienie elastyczności i rozciągliwości kodu. Metoda GenerateTotal w klasie ShoppingCartModel może robić więcej niż tylko obliczać rabaty. Może również obsługiwać zadania takie jak sprawdzanie dostępności zapasów, walidacja zawartości koszyka lub inna logika biznesowa. Delegaty pozwalają na przekazywanie konkretnych metod do unikalnych zadań lub niestandardowego zachowania bez zmiany głównej metody. To sprawia, że kod jest bardziej modułowy i łatwiejszy do utrzymania.

Delegaty są szczególnie użyteczne w scenariuszach, gdy chcesz:

  • Zastosować różne zasady lub logikę biznesową dynamicznie.
  • Zachować główną metodę ogólną i wielokrotnego użytku.
  • Wdrożyć niestandardowe zachowanie dla konkretnych przypadków bez modyfikacji głównej metody.

Delegat Action: Tworzenie i Wyjaśnianie

Tim wprowadza delegata Action, kolejny specjalny typ delegata w C#. Delegat Action jest podobny do Func, ale nie zwraca żadnej wartości (czyli zwraca void).

  1. Tworzenie Delegata Action:
  • Zdefiniuj delegata Action w metodzie GenerateTotal, aby obsługiwać alerty lub komunikaty.

    public decimal GenerateTotal(Func<List<ProductModel>, decimal, decimal> calculateDiscountedTotal, Action<string> tellUserWeAreDiscounting)
    {
        decimal subtotal = Items.Sum(x => x.Price);
        MentionSubtotal(subtotal);
    
        tellUserWeAreDiscounting("We are applying your discount.");
    
        return calculateDiscountedTotal(Items, subtotal);
    }
    public decimal GenerateTotal(Func<List<ProductModel>, decimal, decimal> calculateDiscountedTotal, Action<string> tellUserWeAreDiscounting)
    {
        decimal subtotal = Items.Sum(x => x.Price);
        MentionSubtotal(subtotal);
    
        tellUserWeAreDiscounting("We are applying your discount.");
    
        return calculateDiscountedTotal(Items, subtotal);
    }
  1. Tworzenie Metody Alertu:
  • Zdefiniuj metodę, aby pasowała do podpisu delegata Action.

    private static void AlertUser(string message)
    {
        Console.WriteLine(message);
    }
    private static void AlertUser(string message)
    {
        Console.WriteLine(message);
    }
  1. Przekazanie Metody do Delegata Action:
  • Przekaż metodę AlertUser do metody GenerateTotal za pomocą delegata Action.

    class Program
    {
        static ShoppingCartModel cart = new ShoppingCartModel();
    
        static void Main(string[] args)
        {
            PopulateCartWithDemoData();
    
            Console.WriteLine($"The total for the cart is {cart.GenerateTotal(CalculateLevelDiscount, AlertUser):C2}");
    
            Console.ReadLine();
        }
    
        private static void PopulateCartWithDemoData()
        {
            cart.Items.Add(new ProductModel { ItemName = "Cereal", Price = 3.63M });
            cart.Items.Add(new ProductModel { ItemName = "Milk", Price = 2.95M });
            cart.Items.Add(new ProductModel { ItemName = "Strawberries", Price = 7.51M });
            cart.Items.Add(new ProductModel { ItemName = "Blueberries", Price = 6.75M });
        }
    
        private static decimal CalculateLevelDiscount(List<ProductModel> items, decimal subtotal)
        {
            if (subtotal > 100)
            {
                return subtotal * 0.80M;
            }
            else if (subtotal > 50)
            {
                return subtotal * 0.85M;
            }
            else if (subtotal > 10)
            {
                return subtotal * 0.90M;
            }
            else
            {
                return subtotal;
            }
        }
    
        private static void AlertUser(string message)
        {
            Console.WriteLine(message);
        }
    }
    class Program
    {
        static ShoppingCartModel cart = new ShoppingCartModel();
    
        static void Main(string[] args)
        {
            PopulateCartWithDemoData();
    
            Console.WriteLine($"The total for the cart is {cart.GenerateTotal(CalculateLevelDiscount, AlertUser):C2}");
    
            Console.ReadLine();
        }
    
        private static void PopulateCartWithDemoData()
        {
            cart.Items.Add(new ProductModel { ItemName = "Cereal", Price = 3.63M });
            cart.Items.Add(new ProductModel { ItemName = "Milk", Price = 2.95M });
            cart.Items.Add(new ProductModel { ItemName = "Strawberries", Price = 7.51M });
            cart.Items.Add(new ProductModel { ItemName = "Blueberries", Price = 6.75M });
        }
    
        private static decimal CalculateLevelDiscount(List<ProductModel> items, decimal subtotal)
        {
            if (subtotal > 100)
            {
                return subtotal * 0.80M;
            }
            else if (subtotal > 50)
            {
                return subtotal * 0.85M;
            }
            else if (subtotal > 10)
            {
                return subtotal * 0.90M;
            }
            else
            {
                return subtotal;
            }
        }
    
        private static void AlertUser(string message)
        {
            Console.WriteLine(message);
        }
    }

Tworzenie Anonimowych Metod: Anonimowy Delegat

Tim pokazuje, jak używać anonimowych metod, pozwalając na definiowanie metod na bieżąco bez ich nazywania.

  1. Definiowanie Anonimowych Metod:
  • Zamiast tworzyć nazwane metody, możesz definiować metody bezpośrednio tam, gdzie są potrzebne.

    class Program
    {
        static ShoppingCartModel cart = new ShoppingCartModel();
    
        static void Main(string[] args)
        {
            PopulateCartWithDemoData();
    
            Console.WriteLine($"The total for the cart is {cart.GenerateTotal((items, subtotal) => 
            {
                if (subtotal > 100) return subtotal * 0.80M;
                else if (subtotal > 50) return subtotal * 0.85M;
                else if (subtotal > 10) return subtotal * 0.90M;
                else return subtotal;
            },
            (message) => Console.WriteLine(message)):C2}");
    
            Console.ReadLine();
        }
    
        private static void PopulateCartWithDemoData()
        {
            cart.Items.Add(new ProductModel { ItemName = "Cereal", Price = 3.63M });
            cart.Items.Add(new ProductModel { ItemName = "Milk", Price = 2.95M });
            cart.Items.Add(new ProductModel { ItemName = "Strawberries", Price = 7.51M });
            cart.Items.Add(new ProductModel { ItemName = "Blueberries", Price = 6.75M });
        }
    }
    class Program
    {
        static ShoppingCartModel cart = new ShoppingCartModel();
    
        static void Main(string[] args)
        {
            PopulateCartWithDemoData();
    
            Console.WriteLine($"The total for the cart is {cart.GenerateTotal((items, subtotal) => 
            {
                if (subtotal > 100) return subtotal * 0.80M;
                else if (subtotal > 50) return subtotal * 0.85M;
                else if (subtotal > 10) return subtotal * 0.90M;
                else return subtotal;
            },
            (message) => Console.WriteLine(message)):C2}");
    
            Console.ReadLine();
        }
    
        private static void PopulateCartWithDemoData()
        {
            cart.Items.Add(new ProductModel { ItemName = "Cereal", Price = 3.63M });
            cart.Items.Add(new ProductModel { ItemName = "Milk", Price = 2.95M });
            cart.Items.Add(new ProductModel { ItemName = "Strawberries", Price = 7.51M });
            cart.Items.Add(new ProductModel { ItemName = "Blueberries", Price = 6.75M });
        }
    }
  1. Zrozumienie Składni:
  • Składnia anonimowej metody używa operatora => (wyrażenie lambda) do zdefiniowania ciała metody bezpośrednio w linii.
  • Nie ma potrzeby określania typu zwracanego lub nazwy metody.

Dzięki użyciu delegatów, w tym Func, Action i anonimowych metod, deweloperzy mogą tworzyć bardziej dynamiczny i modułowy kod, pozwalając na elastyczne i wielorazowe komponenty.

Użycie Delegatów w Innych Projektach: WinForms

W tym segmencie Tim Corey demonstruje siłę delegatów, rozszerzając ich użycie na aplikację WinForms. To podkreśla, jak delegaty mogą ułatwić różne zachowania w różnych kontekstach interfejsu użytkownika (UI).

Konfiguracja Aplikacji WinForms

  1. WinForm UI z Dwoma Przyciski:
  • Forma ma dwa przyciski: jeden do demonstrowania okienek komunikatów i jeden do demonstrowania pól tekstowych.

  • ShoppingCartModel i metoda do jego wypełnienia danymi demo są również zawarte.
public partial class Dashboard : Form
{
    ShoppingCartModel cart = new ShoppingCartModel();

    public Dashboard()
    {
        InitializeComponent();
        PopulateCartWithDemoData();
    }

    private void PopulateCartWithDemoData()
    {
        cart.Items.Add(new ProductModel { ItemName = "Cereal", Price = 3.63M });
        cart.Items.Add(new ProductModel { ItemName = "Milk", Price = 2.95M });
        cart.Items.Add(new ProductModel { ItemName = "Strawberries", Price = 7.51M });
        cart.Items.Add(new ProductModel { ItemName = "Blueberries", Price = 6.75M });
    }

    private void messageBoxDemoButton_Click(object sender, EventArgs e)
    {
        decimal total = cart.GenerateTotal(SubtotalAlert, CalculateLevelDiscount, PrintOutDiscountAlert);
        MessageBox.Show($"The total is {total:C2}");
    }

    private void textBoxDemoButton_Click(object sender, EventArgs e)
    {
        // Code for TextBox demo will go here
    }
}
public partial class Dashboard : Form
{
    ShoppingCartModel cart = new ShoppingCartModel();

    public Dashboard()
    {
        InitializeComponent();
        PopulateCartWithDemoData();
    }

    private void PopulateCartWithDemoData()
    {
        cart.Items.Add(new ProductModel { ItemName = "Cereal", Price = 3.63M });
        cart.Items.Add(new ProductModel { ItemName = "Milk", Price = 2.95M });
        cart.Items.Add(new ProductModel { ItemName = "Strawberries", Price = 7.51M });
        cart.Items.Add(new ProductModel { ItemName = "Blueberries", Price = 6.75M });
    }

    private void messageBoxDemoButton_Click(object sender, EventArgs e)
    {
        decimal total = cart.GenerateTotal(SubtotalAlert, CalculateLevelDiscount, PrintOutDiscountAlert);
        MessageBox.Show($"The total is {total:C2}");
    }

    private void textBoxDemoButton_Click(object sender, EventArgs e)
    {
        // Code for TextBox demo will go here
    }
}

Tworzenie Metod dla Delegatów

  1. PrintOutDiscountAlert:
  • Ta metoda będzie używana do pokazywania alertu z informacjami o rabacie.

    private void PrintOutDiscountAlert(string message)
    {
        MessageBox.Show(message);
    }
    private void PrintOutDiscountAlert(string message)
    {
        MessageBox.Show(message);
    }
  1. SubtotalAlert:
  • Ta metoda wyświetli sumę częściową w oknie komunikatu.

    private void SubtotalAlert(decimal subtotal)
    {
        MessageBox.Show($"The subtotal is {subtotal:C2}");
    }
    private void SubtotalAlert(decimal subtotal)
    {
        MessageBox.Show($"The subtotal is {subtotal:C2}");
    }
  1. CalculateLevelDiscount:
  • Ta metoda obliczy rabat na podstawie liczby przedmiotów w koszyku.

    private decimal CalculateLevelDiscount(List<ProductModel> items, decimal subtotal)
    {
        if (items.Count > 3)
        {
            return subtotal - 3M;
        }
        return subtotal - items.Count;
    }
    private decimal CalculateLevelDiscount(List<ProductModel> items, decimal subtotal)
    {
        if (items.Count > 3)
        {
            return subtotal - 3M;
        }
        return subtotal - items.Count;
    }

Integracja Delegatów z WinForms

  1. Użycie Delegatów w Zdarzeniu Kliknięcia Przycisku:
  • Metoda messageBoxDemoButton_Click pokazuje, jak przekazać delegaty do metody GenerateTotal i obsługiwać wyniki za pomocą okien komunikatów.

    private void messageBoxDemoButton_Click(object sender, EventArgs e)
    {
        decimal total = cart.GenerateTotal(SubtotalAlert, CalculateLevelDiscount, PrintOutDiscountAlert);
        MessageBox.Show($"The total is {total:C2}");
    }
    private void messageBoxDemoButton_Click(object sender, EventArgs e)
    {
        decimal total = cart.GenerateTotal(SubtotalAlert, CalculateLevelDiscount, PrintOutDiscountAlert);
        MessageBox.Show($"The total is {total:C2}");
    }
  1. Uruchamianie Aplikacji:
  • Gdy przycisk zostanie kliknięty, aplikacja WinForms pokazuje sumę częściową i całkowitą za pomocą okien komunikatów, demonstrując elastyczność delegatów.

    Understanding Csharp Delegate 3 related to Integracja Delegatów z WinForms

Wnioski

Tim Corey jasno wyjaśnia delegaty w C#, omawiając ich podstawy, zaawansowane użycie i praktyczne przykłady, takie jak użycie delegatów w koszyku zakupowym. Pokazuje, jak delegaty umożliwiają elastyczny i wielorazowego użytku kod, w tym Func, Action i anonimowe metody. Obejrzyj pełny film, aby nauczyć się, jak efektywnie stosować delegaty w swoich projektach!

Hero Worlddot related to Zrozumienie delegatów w C#
Hero Affiliate related to Zrozumienie delegatów w C#

Zarabiaj więcej, dzieląc się tym, co kochasz

Tworzysz treści dla deweloperów pracujących z .NET, C#, Java, Python, czy Node.js? Zamień swoją wiedzę specjalistyczną na dodatkowy dochód!

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie