Altbilgi içeriğine atla
Iron Academy Logo
C# öğrenin
C# öğrenin

Diğer Kategoriler

C# Temsilcilerini Anlamak

[[academy-video-youtube({"vid": "R8Blt5c-Vi4", "start_time": "0", "title": "C# Delegate Anlamak", "creator": "Tim Corey", "length": "1h 9m 11s"})]]

C#'ta delegeler güçlü bir özelliktir, ancak birçok geliştirici onların etkili kullanımına aşina değildir. Tim Corey'nin "C#'ta Delegeler - Pratik bir gösterim, Action ve Func dahil" videosu, delege'lerin ne olduğunu, nasıl kullanılacağını ve neden faydalı olduklarını kapsamlı bir şekilde açıklar.

Bu makale, C#'taki delegeler konusunda Tim'in uzman görüşünü verecek ve onların kullanımı ve pratik uygulamaları konusunda net bir açıklama sunacak. Alışveriş sepeti sistemi gibi örneklerle, delegelerin kodunuzun esnekliğini ve verimliliğini nasıl artırabileceğini öğreneceksiniz.

Giriş

Tim, delegelerin C#'taki gücünü ve çok yönlülüğünü vurgulayarak delege kavramını tanıtır. İzleyicilere, bazı korkutucu terimlere rağmen, delegelerin temelinin basit olduğunu garanti ediyor. Tim, delegeleri açıklığa kavuşturmayı ve func ve action gibi özel türleri ele almayı amaçlıyor.

Demo Uygulama Gezintisi

Tim bir delege kullanımını göstermek için bir demo uygulama ayarlıyor. Çözüm üç projeden oluşur: bir Konsol UI, bir Demo Kütüphane ve bir WinForm UI. Odak, başlangıçta Konsol UI ve Demo Kütüphanesi üzerindedir.

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, demo uygulamasının yapısını ve işlevselliğini açıklar:

  • Alışveriş Sepeti Modeli: ÜrünModel listesi ile alışveriş sepetini temsil eder ve ara toplamına göre yapılan indirimlerle toplam maliyeti hesaplar.

  • Ürün Modeli: Ad ve fiyat özellikleri ile bireysel ürünleri temsil eder.

  • Konsol Uygulaması: Sepeti demo verilerle doldurur, toplamı hesaplar ve gösterir.

İndirimleri Anlamak

Tim, ara toplamın uygulanan indirimi belirlediği GenerateTotal yöntemindeki indirim mantığını açıklar:

  • 100$ üzeri ara toplamlar için %20 indirim.
  • 50$ üzeri ara toplamlar için %15 indirim.
  • 10$ üzeri ara toplamlar için %10 indirim.
  • 10$ veya daha az ara toplamlar için indirim yok.

Tim, hesaplama ve indirim mantığını göstermek için bir breakpoint kullanır, böylece izleyicilerin temeli anlamasını sağlar ve ardından delegelere geçer.

Bir Delegeyi Açıklamak ve Oluşturmak

Bu bölümde, Tim Corey C#'ta delegelerin kavramına girer, nasıl çalıştıklarını açıklar ve pratik kod örnekleri ile kullanımlarını gösterir.

Delege Nedir?

Tim, bir delegenin esasen yöntemleri parametre olarak iletme yolu olduğunu açıklar. Bir değişken veya özellik iletmek yerine, bir yöntem iletersiniz, bu da daha esnek ve yeniden kullanılabilir kod sağlar.

Delege Oluşturma ve Kullanma

İşte Tim'in bir delege oluşturma ve kullanma sürecini nasıl parçaladığı:

  1. Delegeyi Tanımla:

    • Delege, dönüş türü ve parametre türlerini belirterek sınıfın en üstünde tanımlanır.
    public delegate void MentionDiscount(decimal subtotal);
    public delegate void MentionDiscount(decimal subtotal);
    • Bu delege, void döndüren ve bir decimal parametresi alan bir yöntemi ifade eder.
  2. Delegeyi Bir Yöntemde Kullanma:

    • Delege, ShoppingCartModel sınıfının GenerateTotal yönteminde bir parametre olarak kullanılır.
    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;
        }
    }
  3. Delegeye İletilecek Bir Yöntem Oluşturma:

    • Delegenin imzasına uygun bir yöntem, Program sınıfında oluşturulur.
    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}");
    }
  4. GenerateTotal Yöntemini Çağırma:

    • Yöntem, delege aracılığıyla GenerateTotal yöntemine iletilir.
    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 });
        }
    }

Uygulamayı Çalıştırma

Tim, delegenin nasıl çalıştığını göstermek için uygulamayı çalıştırır. Konsol çıktısı, ara toplamı ve sepet için toplamı gösterir ve SubtotalAlert yönteminin delege aracılığıyla başarıyla iletilip yürütüldüğünü belirtir.

Understanding Csharp Delegate 1 related to Uygulamayı Çalıştırma

Func ve Action: Delegelerle Çözebileceğiniz Sorunlar

Tim Corey daha sonra C#'ta func ve action delegelerinin kullanımını araştırır. Bunlar, generics ile delege kullanımını basitleştirmek için Microsoft tarafından sağlanan özel delege türleridir.

Sorunu Belirleme

Tim, GenerateTotal yönteminde sabit kodlanmış indirim mantığı gibi yaygın bir soruna dikkat çeker. Bu yaklaşım esnek değildir ve indirim kuralları değiştiğinde kod değişiklikleri, derleme ve yeniden dağıtım gerektirir.

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;
    }
}

Func Delegeyi Tanıtma

Tim, sabit kodlu indirim sorununu ele almak için func delegesini tanıtır. Func delegesi, dönüş türü ve 16'ya kadar giriş parametresi ile bir yöntem imzasını temsil eden genel bir delege türüdür.

  1. Func Delegeyi Tanımlama:

    • Func delegesi, indirim hesaplamalarını dinamik olarak ele almak için GenerateTotal yönteminde kullanılır.
    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);
    }
  2. İndirim Hesaplama Yöntemini Oluşturma:

    • Func delegesinin imzasına uygun bir yöntem, Program sınıfında oluşturulur.
    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;
        }
    }
  3. Func Delegeye Yöntemi Geçirme:

    • CalculateLevelDiscount yöntemi, func delegesi aracılığıyla GenerateTotal yöntemine iletilir.
    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;
            }
        }
    }

Uygulamayı Çalıştırma

Tim, değiştirilmiş uygulamayı gösterir ve sağlanan mantığa göre indirimlerin doğru şekilde hesaplandığını ve dinamik olarak çalıştığını gösterir.

Understanding Csharp Delegate 2 related to Uygulamayı Çalıştırma

Delege ve Func Arasındaki Farklar

Tim, özel delege ve func delegesini karşılaştırır:

  • Delege: İmzanın açıkça tanımlanmasını gerektiren, net dokümantasyon ve yapı sağlayan.

  • Func: Daha özlü, ancak her seferinde giriş ve çıkış türlerini belirtmeyi gerektirir, bu da daha az net olabilir.

Her iki yaklaşım da esneklik sunar, ancak seçim, uygulamanın özel kullanım durumu ve karmaşıklığına bağlıdır.

Tüm İşler Başka Yerde Yapılıyorsa Neden Delegeleri Kullanmalı?

Tim Corey, delegelerin kullanımıyla ilgili yaygın bir sorunu ele alır: Tüm işler başka yerde yapılıyorsa neden bir delegeye sahip olmalı?

Tim, delegelerin amacının kodda esneklik ve genişletilebilirlik sağlamak olduğunu açıklar. ShoppingCartModel sınıfındaki GenerateTotal yöntemi sadece indirimleri hesaplamakla kalmaz. Ayrıca stok kullanılabilirliğini kontrol etmek, sepet içeriğini doğrulamak veya diğer iş mantıklarını da ele alabilir. Delegeler, özel görevler veya özel davranışlar için özgün yöntemleri çekirdek yöntemi değiştirmeden iletmenize olanak tanır. Bu, kodu daha modüler ve bakımı daha kolay hale getirir.

Delegeler özellikle aşağıdaki senaryolarda kullanışlıdır:

  • Farklı iş kuralları veya mantıkları dinamik olarak uygulamak.
  • Çekirdek yöntemi genel ve yeniden kullanılabilir tutmak.
  • Çekirdek yöntemi değiştirmeden belirli durumlar için özel davranış uygulamak.

Action Delegate: Oluşturmak ve Açıklamak

Tim, C#'ta başka bir özel delege türü olan Action delegesini tanıtır. Action delegesi, Func gibi benzer, ancak bir değer döndürmez (yani, void döner).

  1. Action Delegeyi Oluşturma:

    • Action delegesini GenerateTotal yönteminde uyarı veya mesajları ele almak için tanımlayın.
    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);
    }
  2. Uyarı Yöntemini Oluşturma:

    • Action delegesinin imzasına uygun bir yöntem tanımlayın.
    private static void AlertUser(string message)
    {
        Console.WriteLine(message);
    }
    private static void AlertUser(string message)
    {
        Console.WriteLine(message);
    }
  3. Yöntemi Action Delegeye Geçirme:

    • AlertUser yöntemini Action delegesi aracılığıyla GenerateTotal yöntemine iletin.
    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);
        }
    }

Anonim Yöntemler Oluşturma: Anonim Delege

Tim, adlandırmadan yöntemleri tanımlamanıza olanak tanıyan anonim yöntemlerin nasıl kullanılacağını gösterir.

  1. Anonim Yöntemler Tanımlama:

    • Adlandırılmış yöntemler oluşturmaktansa, ihtiyaç duyulan yerde doğrudan yöntemleri tanımlayabilirsiniz.
    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 });
        }
    }
  2. Sözdizimini Anlamak:

    • Anonim yöntem söz dizimi, yöntem gövdesini doğrudan satır içi tanımlamak için => operatörünü (lambda ifadesi) kullanır.
    • Dönüş türünü veya yöntem adını belirtmeye gerek yoktur.

Delegeleri, Func, Action ve anonim yöntemler dahil kullanarak, geliştiriciler daha dinamik ve modüler kodlar oluşturabilir ve bu da esnek ve yeniden kullanılabilir bileşenler sağlar.

Diğer Projelerde Delegeleri Kullanma: WinForms

Bu segmentte, Tim Corey, delegelerin kullanımını bir WinForms uygulamasına genişleterek delegelerin gücünü gösterir. Bu, delegelerin farklı kullanıcı arayüzü (UI) bağlamlarında farklı davranışları kolaylaştırabildiğini vurgular.

WinForms Uygulamasını Kurma

  1. İki Düğmeli WinForm UI:

    • Formda bir mesaj kutusunu ve bir metin kutusunu göstermek için iki düğme bulunmaktadır.

    • ShoppingCartModel ve onu demo verilerle doldurmak için bir yöntem de dahildir.
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
    }
}

Delegeler için Yöntemler Oluşturma

  1. İndirim Uyarısını Yazdır:

    • Bu yöntem, indirim bilgisiyle bir uyarı göstermek için kullanılacaktır.
    private void PrintOutDiscountAlert(string message)
    {
        MessageBox.Show(message);
    }
    private void PrintOutDiscountAlert(string message)
    {
        MessageBox.Show(message);
    }
  2. Ara Toplam Uyarısı:

    • Bu yöntem, ara toplamı bir mesaj kutusunda gösterecektir.
    private void SubtotalAlert(decimal subtotal)
    {
        MessageBox.Show($"The subtotal is {subtotal:C2}");
    }
    private void SubtotalAlert(decimal subtotal)
    {
        MessageBox.Show($"The subtotal is {subtotal:C2}");
    }
  3. Seviye İndirimlerini Hesapla:

    • Bu yöntem, sepetteki ürünlerin sayısına göre indirimi hesaplayacaktır.
    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;
    }

Delegeleri WinForms ile Entegre Etme

  1. Düğme Tıklama Olayında Delegeleri Kullanma:

    • messageBoxDemoButton_Click yöntemi, delegelerin GenerateTotal yöntemine nasıl geçirileceğini ve sonuçların mesaj kutularıyla nasıl işleneceğini gösterir.
    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}");
    }
  2. Uygulamayı Çalıştırma:

    • Düğme tıklandığında, WinForms uygulaması mesaj kutuları kullanarak ara toplamı ve toplamı gösterir ve delegelerin esnekliğini gösterir.

    Understanding Csharp Delegate 3 related to Delegeleri WinForms ile Entegre Etme

Sonuç

Tim Corey, C#'ta delegeleri net bir şekilde açıklar, temellerini, ileri düzey kullanımını ve alışveriş sepetinde gibi pratik örnekleri kapsar. Delegeler, esnek ve yeniden kullanılabilir kodlar oluşturmanızı sağlar, Func, Action ve anonim yöntemler dahil. Projelerinizde delegeleri etkili bir şekilde nasıl uygulayacağınızı öğrenmek için tam videoyu izleyin!

Hero Worlddot related to C# Temsilcilerini Anlamak
Hero Affiliate related to C# Temsilcilerini Anlamak

Sevdiğiniz Şeyleri Paylaşarak Daha Fazla Kazanın

.NET, C#, Java, Python veya Node.js ile çalışan geliştiriciler için içerik oluşturuyor musunuz? Uzmanlığınızı ek gelire dönüştürün!

Iron Destek Ekibi

Haftada 5 gün, 24 saat çevrimiçiyiz.
Sohbet
E-posta
Beni Ara