在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
C# 泛型引入了一種方法來設計類別、方法、介面和委派,其中他們管理的數據類型可以指定為參數。這種概念稱為泛型類型參數,允許創建靈活且可重複使用的代碼組件。通過使用 泛型,您可以最大化代碼重用性、類型安全性和性能。例如,一個通用類可以定義一次,但可以用各種數據類型實例化,提供多樣性和類型完整性。在本文中,我們將學習C# Generics的基礎知識和 IronPDF 庫.
在 C# 中,泛型類別是一種用來創建帶有佔位符的類別的藍圖,用來代表它包含或操作的類型。這個佔位符通常用 T 表示,是在實例化類別時指定的類型參數。我們可以創建具有類型參數 T 的泛型類別來處理各種數據類型。泛型類別對於集合類別(如列表、隊列和哈希表)特別有用,因為它們可以包含任何數據類型,同時確保類型安全並減少類型轉換的需求。
考慮一個名為 Box 的泛型類別,該類別被設計用來存儲任何類型的值:
public class Box<T>
{
private T data;
public Box(T data) { this.data = data; }
public T Data { get { return data; } }
}
public class Box<T>
{
private T data;
public Box(T data) { this.data = data; }
public T Data { get { return data; } }
}
Public Class Box(Of T)
'INSTANT VB NOTE: The field data was renamed since Visual Basic does not allow fields to have the same name as other class members:
Private data_Conflict As T
Public Sub New(ByVal data As T)
Me.data_Conflict = data
End Sub
Public ReadOnly Property Data() As T
Get
Return data_Conflict
End Get
End Property
End Class
要使用這個類別,您需要建立一個實例並具體指定 T 的實際類型:
Box<int> integerBox = new Box<int>(123);
Box<string> stringBox = new Box<string>("Hello");
Box<int> integerBox = new Box<int>(123);
Box<string> stringBox = new Box<string>("Hello");
Dim integerBox As New Box(Of Integer)(123)
Dim stringBox As New Box(Of String)("Hello")
這段程式碼說明了一個單一類別如何 (框
泛型方法類似於泛型類別,但在方法層級定義了型別參數。這允許在非泛型類別或泛型類別中定義可以操作不同型別的方法。
這裡有一個方法,可以交換任何類型的陣列中的兩個元素:
public class Utility
{
public static void Swap<T>(ref T lhs, ref T rhs)
{
T temp = lhs;
lhs = rhs;
rhs = temp;
}
}
public class Utility
{
public static void Swap<T>(ref T lhs, ref T rhs)
{
T temp = lhs;
lhs = rhs;
rhs = temp;
}
}
Public Class Utility
Public Shared Sub Swap(Of T)(ByRef lhs As T, ByRef rhs As T)
Dim temp As T = lhs
lhs = rhs
rhs = temp
End Sub
End Class
上述方法的使用方式如下:
int a = 1, b = 2;
Utility.Swap<int>(ref a, ref b);
string first = "world", second = "hello";
Utility.Swap(ref first, ref second);
int a = 1, b = 2;
Utility.Swap<int>(ref a, ref b);
string first = "world", second = "hello";
Utility.Swap(ref first, ref second);
Dim a As Integer = 1, b As Integer = 2
Utility.Swap(Of Integer)(a, b)
Dim first As String = "world", second As String = "hello"
Utility.Swap(first, second)
泛型介面與委派允許定義可以操作任何類型的合約和回調方法。在您的類別或方法中實作泛型介面或使用泛型委派可以提升靈活性和代碼重用性。
數據訪問操作的泛型存儲庫接口可能如下所示:
public interface IRepository<T>
{
void Add(T item);
T GetById(int id);
IEnumerable<T> GetAll();
}
public interface IRepository<T>
{
void Add(T item);
T GetById(int id);
IEnumerable<T> GetAll();
}
Public Interface IRepository(Of T)
Sub Add(ByVal item As T)
Function GetById(ByVal id As Integer) As T
Function GetAll() As IEnumerable(Of T)
End Interface
此介面可由任何類別實現,以處理特定的資料類型,允許在不同類型之間使用一致的資料存取模式。
可以使用泛型委派來定義類型安全的回呼函數:
public delegate void Action<T>(T item);
public delegate void Action<T>(T item);
Public Delegate Sub Action(Of T)(ByVal item As T)
泛型集合類別,如 List
List<string> names = new List<string>();
names.Add("Alice");
names.Add("Bob");
Dictionary<int, string> keyValuePairs = new Dictionary<int, string>();
keyValuePairs.Add(1, "One");
keyValuePairs.Add(2, "Two");
List<string> names = new List<string>();
names.Add("Alice");
names.Add("Bob");
Dictionary<int, string> keyValuePairs = new Dictionary<int, string>();
keyValuePairs.Add(1, "One");
keyValuePairs.Add(2, "Two");
Dim names As New List(Of String)()
names.Add("Alice")
names.Add("Bob")
Dim keyValuePairs As New Dictionary(Of Integer, String)()
keyValuePairs.Add(1, "One")
keyValuePairs.Add(2, "Two")
除了使用內建的泛型類型,您還可以創建自己的泛型類型,以封裝在不同數據類型之間常見但需要以特定類型方式處理的操作。這種方法對於構建將與各種數據類型一起使用的庫、框架或工具特別有用。
考慮一個泛型 Result 類,它封裝了操作結果以及一個成功標誌和一個可選的消息:
public class Result<T>
{
public bool Success { get; private set; }
public T Data { get; private set; }
public string Message { get; private set; }
public Result(bool success, T data, string message = "")
{
Success = success;
Data = data;
Message = message;
}
}
public class Result<T>
{
public bool Success { get; private set; }
public T Data { get; private set; }
public string Message { get; private set; }
public Result(bool success, T data, string message = "")
{
Success = success;
Data = data;
Message = message;
}
}
Public Class Result(Of T)
Private privateSuccess As Boolean
Public Property Success() As Boolean
Get
Return privateSuccess
End Get
Private Set(ByVal value As Boolean)
privateSuccess = value
End Set
End Property
Private privateData As T
Public Property Data() As T
Get
Return privateData
End Get
Private Set(ByVal value As T)
privateData = value
End Set
End Property
Private privateMessage As String
Public Property Message() As String
Get
Return privateMessage
End Get
Private Set(ByVal value As String)
privateMessage = value
End Set
End Property
Public Sub New(ByVal success As Boolean, ByVal data As T, Optional ByVal message As String = "")
Me.Success = success
Me.Data = data
Me.Message = message
End Sub
End Class
IronPDF 是一個為 .NET 開發人員設計的綜合庫,可在其應用程式中創建、編輯和提取 PDF 文件。IronPDF 有助於 從 HTML 生成 PDF, 編輯現有的 PDF、將 PDF 轉換為圖像等。雖然 IronPDF 本身並不是基於泛型,但理解如何在 C# 環境中與此庫互動,可以大大提升應用程式的文檔管理能力。
這裡使用泛型的想法是建立一個可重用的方法,可以從任何給定的 HTML 字串生成 PDF。這個方法將是泛型的,允許我們根據需要指定不同類型的元數據或配置。
首先,讓我們定義一個簡單的泛型類,它將包含我們的 PDF 生成選項。為了演示目的,這個類將是基本的,但您可以根據需要擴展更多屬性。
public class PdfOptions<T>
{
public T Metadata { get; set; }
public string HtmlContent { get; set; }
}
public class PdfOptions<T>
{
public T Metadata { get; set; }
public string HtmlContent { get; set; }
}
Public Class PdfOptions(Of T)
Public Property Metadata() As T
Public Property HtmlContent() As String
End Class
現在,讓我們使用IronPDF和我們的PdfOptions來創建一個生成PDF的靜態方法。
public static class PdfGenerator
{
public static void GeneratePdf<T>(PdfOptions<T> options)
{
// Initialize the IronPDF HtmlToPdf renderer
var renderer = new ChromePdfRenderer();
// Optional: Apply any renderer options here. For example, setting the paper size.
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
// Generate the PDF from HTML content
var pdfDocument = renderer.RenderHtmlAsPdf(options.HtmlContent);
// Optional: Here, you can use options.Metadata in some way, depending on your generic type T.
// For simplicity, we're just printing the metadata to console if it's of type string.
if (options.Metadata is string metadataString)
{
Console.WriteLine($"Metadata: {metadataString}");
}
// Save the PDF to a file
var fileName = $"GeneratedPdf_{DateTime.Now.Ticks}.pdf";
pdfDocument.SaveAs(fileName);
Console.WriteLine($"PDF generated and saved as {fileName}");
}
}
public static class PdfGenerator
{
public static void GeneratePdf<T>(PdfOptions<T> options)
{
// Initialize the IronPDF HtmlToPdf renderer
var renderer = new ChromePdfRenderer();
// Optional: Apply any renderer options here. For example, setting the paper size.
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
// Generate the PDF from HTML content
var pdfDocument = renderer.RenderHtmlAsPdf(options.HtmlContent);
// Optional: Here, you can use options.Metadata in some way, depending on your generic type T.
// For simplicity, we're just printing the metadata to console if it's of type string.
if (options.Metadata is string metadataString)
{
Console.WriteLine($"Metadata: {metadataString}");
}
// Save the PDF to a file
var fileName = $"GeneratedPdf_{DateTime.Now.Ticks}.pdf";
pdfDocument.SaveAs(fileName);
Console.WriteLine($"PDF generated and saved as {fileName}");
}
}
Public Module PdfGenerator
Public Sub GeneratePdf(Of T)(ByVal options As PdfOptions(Of T))
' Initialize the IronPDF HtmlToPdf renderer
Dim renderer = New ChromePdfRenderer()
' Optional: Apply any renderer options here. For example, setting the paper size.
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4
' Generate the PDF from HTML content
Dim pdfDocument = renderer.RenderHtmlAsPdf(options.HtmlContent)
' Optional: Here, you can use options.Metadata in some way, depending on your generic type T.
' For simplicity, we're just printing the metadata to console if it's of type string.
Dim tempVar As Boolean = TypeOf options.Metadata Is String
Dim metadataString As String = If(tempVar, CStr(options.Metadata), Nothing)
If tempVar Then
Console.WriteLine($"Metadata: {metadataString}")
End If
' Save the PDF to a file
Dim fileName = $"GeneratedPdf_{DateTime.Now.Ticks}.pdf"
pdfDocument.SaveAs(fileName)
Console.WriteLine($"PDF generated and saved as {fileName}")
End Sub
End Module
最後,讓我們使用 PdfGenerator 類來生成 PDF 文件。在此範例中,Metadata 屬性可以是一個包含標題或其他任何相關資訊的字串。
class Program
{
static void Main(string [] args)
{
License.LicenseKey = "License-Key";
var options = new PdfOptions<string>
{
HtmlContent = "<h1>Hello, World!</h1><p>This is a test PDF document generated from HTML.</p>",
Metadata = "Test PDF Title"
};
PdfGenerator.GeneratePdf(options);
}
}
class Program
{
static void Main(string [] args)
{
License.LicenseKey = "License-Key";
var options = new PdfOptions<string>
{
HtmlContent = "<h1>Hello, World!</h1><p>This is a test PDF document generated from HTML.</p>",
Metadata = "Test PDF Title"
};
PdfGenerator.GeneratePdf(options);
}
}
Friend Class Program
Shared Sub Main(ByVal args() As String)
License.LicenseKey = "License-Key"
Dim options = New PdfOptions(Of String) With {
.HtmlContent = "<h1>Hello, World!</h1><p>This is a test PDF document generated from HTML.</p>",
.Metadata = "Test PDF Title"
}
PdfGenerator.GeneratePdf(options)
End Sub
End Class
此範例說明了如何將 IronPDF 與 C# 泛型整合的基本原理,提供了一種靈活的方式從 HTML 內容生成 PDF,同時允許通過泛型 PdfOptions 自訂元數據或配置。
C# 泛型是開發高品質、可重用和類型安全代碼的強大工具。通過理解和應用泛型類、方法、接口和委託,您可以編寫更具適應性且更易於維護的代碼。泛型不僅使代碼可以在不同數據類型之間重用,還能確保編譯時進行類型檢查,從而減少運行時錯誤並提高整體代碼質量。IronPDF 提供了一個 免費試用 費用自$749起。