C# Temsilcilerini Anlamak
C#'de delegeler güçlü bir özelliktir, ancak birçok geliştirici etkili kullanımlarına aşina değildir. Tim Corey'nin "C#'de Delegeler - Eylem ve Func İçeren Pratik Bir Gösterim" videosu, delegelerin ne olduğunu, nasıl kullanılacağını ve neden faydalı olduklarını ayrıntılı olarak açıklar.
Bu makale, Tim'in C#'de delegeler konusundaki uzman görüşlerini size sunarak, kullanım ve pratik uygulamaları hakkında net bir açıklama sağlar. Delegelerin, alışveriş sepeti sistemi gibi örneklerle kodunuzun esnekliğini ve verimliliğini nasıl artırabileceğini öğreneceksiniz.
Giriş
Tim, delegelerin kavramını tanıtarak C#'deki güç ve çok yönlülüklerini vurgular. Bazı göz korkutucu terminolojiye rağmen, delegelerin temelinin basit olduğunu izleyicilere garanti eder. Tim, delegeleri anlaşılır hale getirmeyi ve func ve action gibi özel türleri ele almayı hedefler.
Demo Uygulama Yürütümü
Tim, delegelerin kullanımını göstermek için bir demo uygulaması hazırlar. Çözüm, bir Konsol UI, bir Demo Kütüphanesi ve bir WinForm UI olmak üzere üç proje içerir. Dikkat 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ün modeli listesini içeren alışveriş sepetini temsil eder ve ara toplamına dayalı olarak indirimleri hesaplar.
Ürün Modeli: İsim ve fiyat özellikleri ile bireysel ürünleri temsil eder.
- Konsol Uygulaması: Demo verilerle sepeti doldurur, toplamı hesaplar ve görüntüler.
İndirimleri Anlamak
Tim, GenerateTotal metodundaki indirim mantığını açıklayarak ara toplamın uygulanacak indirimi nasıl belirlediğini açıklar:
- $100 üstündeki ara toplamlar için %20 indirim.
- $50 üstündeki ara toplamlar için %15 indirim.
- $10 üstündeki ara toplamlar için %10 indirim.
- $10 veya daha az olan ara toplamlar için indirim yok.
Tim, izleyicilerin delegelere geçmeden önce temeli anlamalarını sağlamak için hesaplama ve indirim mantığını göstermek amacıyla bir breakpoint kullanır.
Bir Delegeyi Açıklama ve Oluşturma
Bu bölümde Tim Corey, C#'deki delegelerin kavramına derinlemesine girerek nasıl çalıştıklarını açıklar ve pratik kod örnekleriyle kullanımını gösterir.
Delege Nedir?
Tim, bir delegenin esasen metodları parametre olarak geçmenin bir yolu olduğunu açıklar. Bir değişken veya özelliği geçirmek yerine, bir yöntemi geçirirsiniz, bu da daha esnek ve yeniden kullanılabilir bir kod sağlar.
Bir Delegeyi Oluşturma ve Kullanma
İşte Tim'in bir delegeyi oluşturma ve kullanma sürecini nasıl açıkladığı:
Delegeyi Tanımlama:
- Delege, sınıfın en üstünde tanımlanır ve dönüş türü ile parametre türlerini belirtir.
public delegate void MentionDiscount(decimal subtotal);public delegate void MentionDiscount(decimal subtotal);- Bu delege, bir decimal alan ve void döndüren bir metod belirtir.
Delegeyi Bir Metodda Kullanma:
- Delege, ShoppingCartModel sınıfının GenerateTotal metodunda 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; } }Delegeye Geçilecek Yöntemi Oluşturma:
- Delegenin imzasına uygun bir metod 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}"); }GenerateTotal Metodunu Çağırma:
- Metod, delege yoluyla GenerateTotal metoduna geçirilir.
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ı, SubtotalAlert metodunun başarılı bir şekilde geçtiği ve delege yoluyla çalıştırıldığını, sepet için ara toplam ve toplamı gösterir.

Func ve Action: Delegelerle Çözebileceğiniz Sorunlar
Tim Corey, ardından C#'de func ve action delegelerini incelemektedir. Bunlar, Microsoft tarafından generics ile delege kullanımını basitleştirmek için sağlanan özel türde delegelerdir.
Sorunu Belirleme
Tim, GenerateTotal metodundaki sabit kodlanmış indirim mantığını vurgulayan yaygın bir sorunu işaret eder. Bu yaklaşım esnek değildir ve indirim kuralları her değiştiğinde kod değişikliklerine, derlemeye ve yeniden dağıtıma ihtiyaç duyar.
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 kodlanmış indirim sorununu çözmek için func delegeyi tanıtır. Func delege, bir dönüş türü ve 16'ya kadar giriş parametresi içeren bir metod imzasını temsil eden genel bir delegedir.
Func Delege Tanımlama:
- Func delege, GenerateTotal metodunda indirim hesaplamalarını dinamik olarak ele almak için 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); }İndirim Hesaplama Metodunu Oluşturma:
- Func delegenin imzasına uygun bir metod 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; } }Metodu Func Delegeye Geçme:
- CalculateLevelDiscount metodu, Func delege aracılığıyla GenerateTotal metoduna geçirilir.
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, sağlanan mantığa dayalı olarak indirimi doğru ve dinamik olarak hesaplayan değiştirilmiş uygulamayı gösterir.

Delege ve Func Arasındaki Farklar
Tim, özel delege ve func delegeyi karşılaştırır:
Delege: İmzanın açıkça tanımlanmasını gerektirir, net bir belge ve yapı sağlar.
- Func: Daha kısa 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.
Çalışmanın Tümü Başka Yerdeyse Neden Delegeleri Kullanmalısınız?
Tim Corey, delegelerin kullanımına ilişkin yaygın bir soruya değinir: Tüm iş başka yerde yapılıyorsa neden delegeye sahip olmalısınız?
Tim, delegelerin amacının kodda esneklik ve genişletilebilirlik sağlamak olduğunu açıklar. ShoppingCartModel sınıfındaki GenerateTotal metodu, yalnızca indirimleri hesaplamaktan daha fazlasını yapabilir. Stok mevcudiyetini kontrol etme, sepet içeriğini doğrulama veya diğer iş mantıklarını da yapabilir. Delegeler, belirli görevler veya özel davranışlar için, ana metodu değiştirmeden, belirli metodlar geçirmenize izin verir. Bu, kodu daha modüler ve bakımı kolay hale getirir.
Delegeler, özellikle şu senaryolarda kullanışlıdır:
- İş kuralları veya mantığı dinamik olarak uygulama.
- Ana metodu genel ve yeniden kullanılabilir tutma.
- Ana metodu değiştirmeden belirli durumlar için özel davranışları uygulama.
Action Delegesi: Oluşturma ve Açıklama
Tim, C#'deki başka bir özel delege türü olan Action delegesini tanıtır. Action delegesi, Func'a benzerdir, ancak bir değer döndürmez (yani, void döndürür).
Action Delegesi Oluşturma:
- GenelTotal metodunda uyarılar veya mesajları ele almak için Action delegeyi 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); }Uyarı Metodunu Oluşturma:
- Action delegenin imzasına uyan bir metod tanımlayın.
private static void AlertUser(string message) { Console.WriteLine(message); }private static void AlertUser(string message) { Console.WriteLine(message); }Metodu Action Delegeye Geçme:
- AlertUser metodunu Action delege aracılığıyla GenerateTotal metoduna geçirin.
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 Metodlar Oluşturma: Anonim Delege
Tim, isimlendirmeden metodları tanımlama olanağı sağlamaya olanak tanıyan anonim metodları nasıl kullanacağını gösterir.
Anonim Metodları Tanımlama:
- İsimlendirilmiş metodlar yaratmak yerine, metodları ihtiyaç duyuldukları yere doğrudan 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 }); } }Sözdizimini Anlamak:
- Anonim metod sözdizimi, metod gövdesini doğrudan satır içinde tanımlamak için
=>operatörünü (lambda ifadesi) kullanır. - Geri dönüş türünü veya metod adını belirtmeye gerek yoktur.
- Anonim metod sözdizimi, metod gövdesini doğrudan satır içinde tanımlamak için
Delegeler, Func, Action ve anonim metodlar dahil olmak üzere, geliştiricilerin daha dinamik ve modüler kodlar yaratmalarını sağlar, esnek ve yeniden kullanılabilir bileşenler oluşturur.
Başka Projelerde Delegeleri Kullanmak: WinForms
Bu bölümde, Tim Corey, delegelerin gücünü genişleterek bir WinForms uygulamasına kullanımlarını gösterir. Bu, delegelerin çeşitli kullanıcı arabirimi (UI) bağlamlarında farklı davranışları nasıl kolaylaştırabileceğini vurgular.
WinForms Uygulamasını Hazırlama
İki Düğmeli WinForm UI:
Formda iki düğme vardır: biri mesaj kutularını göstermek, diğeri ise metin kutularını göstermek içindir.
- ShoppingCartModel ve demo verilerle doldurmak için bir metod da dahil edilmiştir.
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 Metodlar Oluşturma
PrintOutDiscountAlert:
- Bu yöntemle indirim bilgileri içeren bir uyarı gösterilecektir.
private void PrintOutDiscountAlert(string message) { MessageBox.Show(message); }private void PrintOutDiscountAlert(string message) { MessageBox.Show(message); }SubtotalAlert:
- Bu yöntemle ara toplam bir mesaj kutusunda gösterilecektir.
private void SubtotalAlert(decimal subtotal) { MessageBox.Show($"The subtotal is {subtotal:C2}"); }private void SubtotalAlert(decimal subtotal) { MessageBox.Show($"The subtotal is {subtotal:C2}"); }CalculateLevelDiscount:
- Bu yöntemle, sepet içindeki öğelerin sayısına bağlı olarak indirim hesaplanacaktı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
Düğme Tıklama Olayında Delegeleri Kullanma:
messageBoxDemoButton_Clickmetodu, delegeleri GenerateTotal metoduna nasıl geçireceğinizi ve sonuçları mesaj kutuları kullanarak nasıl ele alacağınızı 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}"); }Uygulamayı Çalıştırma:
- Düğme tıklandığında, WinForms uygulaması ara toplamı ve toplamı mesaj kutuları kullanarak gösterir, delegelerin esnekliğini gösterir.

Sonuç
Tim Corey, C#'de delegeleri, onların temellerini, ileri düzey kullanımını ve alışveriş sepeti gibi delegeleri kullanma gibi pratik örneklerle açıklar. Func, Action ve anonim metodlar dahil olmak üzere delegelerin, esnek ve yeniden kullanılabilir kodları nasıl sağladığını gösterir. Tam videoyu izleyerek projelerinizde delegeleri etkili bir şekilde nasıl uygulayabileceğinizi öğrenin!

