Earn More by Sharing What You Love
Do you create content for developers working with .NET, C#, Java, Python, or Node.js? Turn your expertise into extra income!

Tim Corey
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.
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.
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; }
}Imports System
Imports System.Collections.Generic
Imports System.Linq
Namespace ConsoleUI
Class Program
Private Shared cart As New ShoppingCartModel()
Shared Sub Main(args As String())
PopulateCartWithDemoData()
Console.WriteLine($"The total for the cart is {cart.GenerateTotal():C2}")
Console.ReadLine()
End Sub
Private Shared Sub PopulateCartWithDemoData()
cart.Items.Add(New ProductModel With {.ItemName = "Cereal", .Price = 3.63D})
cart.Items.Add(New ProductModel With {.ItemName = "Milk", .Price = 2.95D})
cart.Items.Add(New ProductModel With {.ItemName = "Strawberries", .Price = 7.51D})
cart.Items.Add(New ProductModel With {.ItemName = "Blueberries", .Price = 6.75D})
End Sub
End Class
End Namespace
Public Class ShoppingCartModel
Public Property Items As List(Of ProductModel) = New List(Of ProductModel)()
Public Function GenerateTotal() As Decimal
Dim subtotal As Decimal = Items.Sum(Function(x) x.Price)
If subtotal > 100 Then
Return subtotal * 0.80D
ElseIf subtotal > 50 Then
Return subtotal * 0.85D
ElseIf subtotal > 10 Then
Return subtotal * 0.90D
Else
Return subtotal
End If
End Function
End Class
Public Class ProductModel
Public Property ItemName As String
Public Property Price As Decimal
End ClassTim, 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.
Tim, ara toplamın uygulanan indirimi belirlediği GenerateTotal yöntemindeki indirim mantığını açıklar:
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.
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.
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.
İşte Tim'in bir delege oluşturma ve kullanma sürecini nasıl parçaladığı:
Delegeyi Tanımla:
public delegate void MentionDiscount(decimal subtotal);Public Delegate Sub MentionDiscount(subtotal As Decimal)Delegeyi Bir Yöntemde Kullanma:
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 İletilecek Bir Yöntem Oluşturma:
private static void SubtotalAlert(decimal subtotal)
{
Console.WriteLine($"The subtotal is {subtotal:C2}");
}
GenerateTotal Yöntemini Çağırma:
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 });
}
}
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.

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.
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 Function GenerateTotal() As Decimal
Dim subtotal As Decimal = Items.Sum(Function(x) x.Price)
If subtotal > 100 Then
Return subtotal * 0.80D
ElseIf subtotal > 50 Then
Return subtotal * 0.85D
ElseIf subtotal > 10 Then
Return subtotal * 0.90D
Else
Return subtotal
End If
End FunctionTim, 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.
Func Delegeyi Tanımlama:
public decimal GenerateTotal(Func<List<ProductModel>, decimal, decimal> calculateDiscountedTotal)
{
decimal subtotal = Items.Sum(x => x.Price);
MentionDiscount(subtotal);
return calculateDiscountedTotal(Items, subtotal);
}
İndirim Hesaplama Yöntemini Oluşturma:
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;
}
}
Func Delegeye Yöntemi Geçirme:
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;
}
}
}
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.

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.
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:
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).
Action Delegeyi Oluşturma:
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ı Yöntemini Oluşturma:
private static void AlertUser(string message)
{
Console.WriteLine(message);
}
Yöntemi Action Delegeye Geçirme:
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);
}
}
Tim, adlandırmadan yöntemleri tanımlamanıza olanak tanıyan anonim yöntemlerin nasıl kullanılacağını gösterir.
Anonim Yöntemler Tanımlama:
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:
=> operatörünü (lambda ifadesi) kullanır.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.
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.
İ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
Inherits Form
Private cart As New ShoppingCartModel()
Public Sub New()
InitializeComponent()
PopulateCartWithDemoData()
End Sub
Private Sub PopulateCartWithDemoData()
cart.Items.Add(New ProductModel With {.ItemName = "Cereal", .Price = 3.63D})
cart.Items.Add(New ProductModel With {.ItemName = "Milk", .Price = 2.95D})
cart.Items.Add(New ProductModel With {.ItemName = "Strawberries", .Price = 7.51D})
cart.Items.Add(New ProductModel With {.ItemName = "Blueberries", .Price = 6.75D})
End Sub
Private Sub messageBoxDemoButton_Click(sender As Object, e As EventArgs) Handles messageBoxDemoButton.Click
Dim total As Decimal = cart.GenerateTotal(AddressOf SubtotalAlert, AddressOf CalculateLevelDiscount, AddressOf PrintOutDiscountAlert)
MessageBox.Show($"The total is {total:C2}")
End Sub
Private Sub textBoxDemoButton_Click(sender As Object, e As EventArgs) Handles textBoxDemoButton.Click
' Code for TextBox demo will go here
End Sub
End Classİndirim Uyarısını Yazdır:
private void PrintOutDiscountAlert(string message)
{
MessageBox.Show(message);
}
Ara Toplam Uyarısı:
private void SubtotalAlert(decimal subtotal)
{
MessageBox.Show($"The subtotal is {subtotal:C2}");
}
Seviye İndirimlerini Hesapla:
private decimal CalculateLevelDiscount(List<ProductModel> items, decimal subtotal)
{
if (items.Count > 3)
{
return subtotal - 3M;
}
return subtotal - items.Count;
}
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}");
}
Uygulamayı Çalıştırma:

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!
Do you create content for developers working with .NET, C#, Java, Python, or Node.js? Turn your expertise into extra income!
Join our newsletter, you’ll get exclusive access on article updates. We value your privacy