
C# Uzantı Yöntemleri (Geliştiriciler İçin Nasıl Çalışır)
Extension yöntemleri, mevcut türlerin kaynak kodunu değiştirmeden yeni işlevsellik eklemenizi sağlayan güçlü bir C# özelliğidir. Kodunuzu daha okunabilir ve sürdürülebilir hale getirmede son derece faydalı olabilirler. Bu kılavuzda, genişletme yöntemlerinin temellerini ve bunların nasıl uygulanacağını inceleyeceğiz.
Genişletme Metotları Nelerdir?
Genişletme metotları, mevcut bir türün örnek metotları gibi çağrılabilen özel statik metotlardır. Mevcut bir sınıfa yeni yöntemler eklemenin, orijinal kaynak kodunu değiştirmeden veya sınıftan türetmeden, kullanışlı bir yoludur.
Bir uzantı metodu oluşturmak için, statik bir sınıf içerisinde statik bir metot tanımlamanız gerekir. Yöntemin ilk parametresi, this anahtar kelimesiyle başlayan, genişletmek istediğiniz tür olmalıdır. Bu özel anahtar kelime, C# derleyicisine bunun bir uzantı metodu olduğunu belirtir.
Implementing Extension Methods in C#
Şimdi uzantı yöntemlerinin ne olduğunu bildiğimize göre, bir tane uygulayalım. Bir dizeyi ters çevirmek istediğinizi hayal edin. Bunu yapmak için ayrı bir fonksiyon yazmak yerine, string sınıfı için bir uzantı metodu oluşturabilirsiniz.
Önce, StringExtensions adında yeni bir statik sınıf oluşturalım. Sınıf adı önemli değildir, ancak yaygın bir konvansiyon olarak genişletilen türün adını, ardından "Extensions" ifadesini kullanmak yaygındır. Bu sınıfın içinde, Reverse adında bir statik yöntem tanımlayacağız:
public static class StringExtensions
{
// This extension method reverses a given string.
public static string Reverse(this string input)
{
// Convert the string to a character array.
char[] chars = input.ToCharArray();
// Reverse the array in place.
Array.Reverse(chars);
// Create a new string from the reversed character array and return it.
return new string(chars);
}
}Public Module StringExtensions
' This extension method reverses a given string.
<System.Runtime.CompilerServices.Extension> _
Public Function Reverse(ByVal input As String) As String
' Convert the string to a character array.
Dim chars() As Char = input.ToCharArray()
' Reverse the array in place.
Array.Reverse(chars)
' Create a new string from the reversed character array and return it.
Return New String(chars)
End Function
End ModuleBu örnekte, tek bir parametre ile Reverse adı verilen genel bir statik dize yöntemi oluşturduk. Dize türünden önceki this anahtar kelimesi, bunun dize sınıfı için bir genişletme yöntemi olduğunu belirtir.
Şimdi, yeni genişletme yöntemimizi Program sınıfımızda nasıl kullanacağımızı görelim:
class Program
{
static void Main(string[] args)
{
string example = "Hello, World!";
// Call the extension method as if it were an instance method.
string reversed = example.Reverse();
Console.WriteLine(reversed); // Output: !dlroW ,olleH
}
}Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim example As String = "Hello, World!"
' Call the extension method as if it were an instance method.
Dim reversed As String = example.Reverse()
Console.WriteLine(reversed) ' Output: !dlroW ,olleH
End Sub
End ClassStringExtensions sınıfının bir örneğini oluşturmak zorunda olmadığımızı fark edin. Bunun yerine, dizgi örneği üzerinde doğrudan Reverse yöntemini bir örnek yöntemiymiş gibi kullandık.
Genişletme Metodu Sözdizimi
Genişletme metotları, görünüm ve davranış açısından örnek metotlara benzer, ancak akılda tutulması gereken birkaç önemli fark vardır:
- Uzantı metotları, genişletilen türün özel üyelerine erişemez. Onlar da kalıtım veya çok biçimlilikte yer almazlar. Var olan bir yöntemi genişletme yöntemi ile geçersiz kılamazsınız.
Genişletilmiş türün bir uzatma yöntemiyle aynı imzaya sahip bir metodu varsa, örnek metodu her zaman öncelikli olacaktır. Genişletme yöntemleri, yalnızca eşleşen bir örnek yöntemi olmadığında çağrılır.
Uzantı Metotlarının Gerçek Hayatta Örnekleri
Artık C#'ta genişletme metodlarının temellerini anladığımıza göre, bazı gerçek hayat örneklerine bakalım.
String Uzantı Metodu Kelime Sayısı
Bir dizgideki kelime sayısını saymak istediğinizi hayal edin. Dize sınıfı için bir WordCount genişletme yöntemi oluşturabilirsiniz:
public static class StringExtensions
{
// This extension method counts the number of words in a string.
public static int WordCount(this string input)
{
// Split the string by whitespace characters and return the length of the resulting array.
return input.Split(new[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
}Imports Microsoft.VisualBasic
Public Module StringExtensions
' This extension method counts the number of words in a string.
<System.Runtime.CompilerServices.Extension> _
Public Function WordCount(ByVal input As String) As Integer
' Split the string by whitespace characters and return the length of the resulting array.
Return input.Split( { " "c, ControlChars.Tab, ControlChars.Cr, ControlChars.Lf }, StringSplitOptions.RemoveEmptyEntries).Length
End Function
End ModuleŞimdi, bir dizedeki kelime sayısını bu şekilde kolayca sayabilirsiniz:
string text = "Extension methods are awesome!";
int wordCount = text.WordCount();
Console.WriteLine($"The text has {wordCount} words."); // Output: The text has 4 words.Dim text As String = "Extension methods are awesome!"
Dim wordCount As Integer = text.WordCount()
Console.WriteLine($"The text has {wordCount} words.") ' Output: The text has 4 words.IEnumerable Uzantı Metodu Median
Sayıların bir koleksiyonuna sahip olduğunuzu ve medyan değerini hesaplamak istediğinizi varsayalım. IEnumerable<int> için bir genişletme yöntemi oluşturabilirsiniz:
using System;
using System.Collections.Generic;
using System.Linq;
public static class EnumerableExtensions
{
// This extension method calculates the median of a collection of integers.
public static double Median(this IEnumerable<int> source)
{
// Sort the collection and convert it to an array.
int[] sorted = source.OrderBy(x => x).ToArray();
int count = sorted.Length;
if (count == 0)
{
throw new InvalidOperationException("The collection is empty.");
}
// If the count is even, return the average of the two middle elements.
if (count % 2 == 0)
{
return (sorted[count / 2 - 1] + sorted[count / 2]) / 2.0;
}
else
{
// Otherwise, return the middle element.
return sorted[count / 2];
}
}
}Imports System
Imports System.Collections.Generic
Imports System.Linq
Public Module EnumerableExtensions
' This extension method calculates the median of a collection of integers.
<System.Runtime.CompilerServices.Extension> _
Public Function Median(ByVal source As IEnumerable(Of Integer)) As Double
' Sort the collection and convert it to an array.
Dim sorted() As Integer = source.OrderBy(Function(x) x).ToArray()
Dim count As Integer = sorted.Length
If count = 0 Then
Throw New InvalidOperationException("The collection is empty.")
End If
' If the count is even, return the average of the two middle elements.
If count Mod 2 = 0 Then
Return (sorted(count \ 2 - 1) + sorted(count \ 2)) / 2.0
Else
' Otherwise, return the middle element.
Return sorted(count \ 2)
End If
End Function
End ModuleBu genişletme yöntemi ile bir koleksiyonun medyan değerini kolayca bulabilirsiniz:
int[] numbers = { 5, 3, 9, 1, 4 };
double median = numbers.Median();
Console.WriteLine($"The median value is {median}."); // Output: The median value is 4.Dim numbers() As Integer = { 5, 3, 9, 1, 4 }
Dim median As Double = numbers.Median()
Console.WriteLine($"The median value is {median}.") ' Output: The median value is 4.DateTime Uzantı Metodu StartOfWeek
Diyelim ki verilen bir tarih için haftanın başlangıcını bulmak istiyorsunuz. DateTime yapısı için bir genişletme yöntemi oluşturabilirsiniz:
public static class DateTimeExtensions
{
// This extension method calculates the start of the week for a given date.
public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek = DayOfWeek.Monday)
{
// Calculate the difference in days between the current day and the start of the week.
int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
// Subtract the difference to get the start of the week.
return dt.AddDays(-1 * diff).Date;
}
}Public Module DateTimeExtensions
' This extension method calculates the start of the week for a given date.
'INSTANT VB NOTE: The parameter startOfWeek was renamed since Visual Basic will not allow parameters with the same name as their enclosing function or property:
<System.Runtime.CompilerServices.Extension> _
Public Function StartOfWeek(ByVal dt As DateTime, Optional ByVal startOfWeek_Conflict As DayOfWeek = DayOfWeek.Monday) As DateTime
' Calculate the difference in days between the current day and the start of the week.
Dim diff As Integer = (7 + (dt.DayOfWeek - startOfWeek_Conflict)) Mod 7
' Subtract the difference to get the start of the week.
Return dt.AddDays(-1 * diff).Date
End Function
End ModuleArtık herhangi bir tarih için haftanın başlangıcını kolayca bulabilirsiniz:
DateTime today = DateTime.Today;
DateTime startOfWeek = today.StartOfWeek();
Console.WriteLine($"The start of the week is {startOfWeek.ToShortDateString()}.");
// Output will depend on the current date, e.g. The start of the week is 17/06/2024.Dim today As DateTime = DateTime.Today
Dim startOfWeek As DateTime = today.StartOfWeek()
Console.WriteLine($"The start of the week is {startOfWeek.ToShortDateString()}.")
' Output will depend on the current date, e.g. The start of the week is 17/06/2024.IronPDF ve Uzantı Yöntemleri ile PDF Oluşturma
Bu bölümde, C# dilinde PDF dosyalarını oluşturmak ve üzerinde çalışmak için endüstri lideri kütüphanemiz IronPDF'yi tanıtacağız. Bu kütüphane ile çalışırken daha sorunsuz ve sezgisel bir deneyim oluşturmak için genişletme yöntemlerinden nasıl faydalanabileceğimizi de göreceğiz.
IronPDF, HTML'yi PDF'ye dönüştürerek içeriğin web tarayıcısında görüneceği şekilde düzen ve stilini korur. Kütüphane, dosyalardan, URL'lerden ve dizelerden gelen ham HTML ile çalışabilir. İşte hızlı bir genel bakış:
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}Imports IronPdf
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim renderer = New ChromePdfRenderer()
' 1. Convert HTML String to PDF
Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")
' 2. Convert HTML File to PDF
Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")
' 3. Convert URL to PDF
Dim url = "http://ironpdf.com" ' Specify the URL
Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
pdfFromUrl.SaveAs("URLToPDF.pdf")
End Sub
End ClassBasit Bir PDF Oluşturma
Uzantı yöntemlerine dalmadan önce, IronPDF kullanarak HTML'den basit bir PDF'nin nasıl oluşturulacağını görelim:
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
var PDF = renderer.RenderHtmlAsPdf("Hello, World!");
PDF.SaveAs("HelloWorld.PDF");
}
}Imports IronPdf
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim renderer = New ChromePdfRenderer()
Dim PDF = renderer.RenderHtmlAsPdf("Hello, World!")
PDF.SaveAs("HelloWorld.PDF")
End Sub
End ClassBu kod parçası, "Hello, World!" metni içeren bir PDF oluşturur ve bunu "HelloWorld.PDF" adlı bir dosyaya kaydeder.
IronPDF için Uzantı Metotları
Şimdi, IronPDF'in işlevselliğini artırmak ve kullanımı daha kolay hale getirmek için uzantı yöntemlerini nasıl kullanabileceğimizi inceleyelim. Örneğin, bir metin sınıfı örneğini alarak doğrudan ondan bir PDF oluşturan bir genişletme yöntemi oluşturabiliriz.
using IronPdf;
public static class StringExtensions
{
// This extension method converts a string containing HTML to a PDF and saves it.
public static void SaveAsPdf(this string htmlContent, string filePath)
{
var renderer = new ChromePdfRenderer();
var PDF = renderer.RenderHtmlAsPdf(htmlContent);
PDF.SaveAs(filePath);
}
}Imports IronPdf
Public Module StringExtensions
' This extension method converts a string containing HTML to a PDF and saves it.
<System.Runtime.CompilerServices.Extension> _
Public Sub SaveAsPdf(ByVal htmlContent As String, ByVal filePath As String)
Dim renderer = New ChromePdfRenderer()
Dim PDF = renderer.RenderHtmlAsPdf(htmlContent)
PDF.SaveAs(filePath)
End Sub
End ModuleBu uzantı metodu ile artık bir dizgiden doğrudan bir PDF oluşturabiliriz:
string html = "<h1>Extension Methods and IronPDF</h1><p>Generating PDFs has never been easier!</p>";
html.SaveAsPdf("ExtensionMethodsAndIronPdf.PDF");Dim html As String = "<h1>Extension Methods and IronPDF</h1><p>Generating PDFs has never been easier!</p>"
html.SaveAsPdf("ExtensionMethodsAndIronPdf.PDF")URL'lerden PDF Oluşturma
Oluşturabileceğimiz bir başka yararlı genişletme yöntemi ise bir URL'den PDF oluşturan bir yöntemdir. Bunu başarmak için Uri sınıfını genişletebiliriz:
using IronPdf;
public static class UriExtensions
{
// This extension method converts a web URL to a PDF and saves it.
public static void SaveAsPdf(this Uri url, string filePath)
{
var renderer = new ChromePdfRenderer();
var PDF = renderer.RenderUrlAsPdf(url.AbsoluteUri);
PDF.SaveAs(filePath);
}
}Imports IronPdf
Public Module UriExtensions
' This extension method converts a web URL to a PDF and saves it.
<System.Runtime.CompilerServices.Extension> _
Public Sub SaveAsPdf(ByVal url As Uri, ByVal filePath As String)
Dim renderer = New ChromePdfRenderer()
Dim PDF = renderer.RenderUrlAsPdf(url.AbsoluteUri)
PDF.SaveAs(filePath)
End Sub
End ModuleArtık, bir URL'den bu şekilde kolayca PDF oluşturabiliriz:
Uri url = new Uri("https://www.ironpdf.com/");
url.SaveAsPdf("UrlToPdf.PDF");Dim url As New Uri("https://www.ironpdf.com/")
url.SaveAsPdf("UrlToPdf.PDF")Sonuç
Ve işte, C#'ta genişletme yöntemleri kavramını inceledik, bunları statik yöntemler ve statik sınıflar kullanarak nasıl uygulayacağımızı öğrendik ve çeşitli türler için gerçek yaşam örnekleri kullandık. Ayrıca, C#'ta PDF dosyaları oluşturmak ve bunlarla çalışmak için bir kütüphane olan IronPDF'yi tanıttık. Extension metodlarını ve IronPDF'i birlikte kullanmaya başladıkça, kodunuzun ne kadar daha temiz, daha okunabilir ve daha verimli hale gelebileceğini göreceksiniz.
IronPDF'yi kullanmaya hazır mısınız? IronPDF'i 30 günlük ücretsiz denememizle başlayabilirsiniz. Geliştirme amaçlı kullanmak tamamen ücretsizdir, böylece gerçekten ne içerdiğini görebilirsiniz. Ve gördüklerinizi beğenirseniz, IronPDF ücretleri liteLicense kadar düşük bir fiyata başlar. Daha büyük tasarruflar için, Iron Software Suite satın alma seçeneklerine göz atın, burada dokuz Iron Software aracının tamamını iki fiyatına alabilirsiniz. İyi kodlamalar!


Jacob Mellor, Iron Software'de Baş Teknoloji Yöneticisidir ve C# PDF teknolojisinde öncü bir mühendisdir. Iron Software'ın ana kod tabanının ilk geliştiricisi olarak, CEO Cameron Rimington ile birlikte şirketin ürün mimarisini 50'den fazla kişilik bir şirkete dönüştürmüştür ve NASA, Tesla ve dünya genelindeki devlet kurumlarına hizmet etmektedir.
İlgili Makaleler


