在实际环境中测试
在生产中测试无水印。
随时随地为您服务。
C# 泛型引入了一种设计类、方法、接口和委托的方法,它们所管理的数据类型可以作为参数指定。这一概念被称为泛型类型参数,它允许创建灵活、可重用的代码组件。通过使用 通用名因此,您可以最大限度地提高代码的可重用性、类型安全性和性能。例如,一个泛型类可以定义一次,但可以用各种数据类型实例化,从而提供了通用性和类型完整性。在本文中,我们将了解 C# 泛型的基础知识和 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 IronPDF 是一个综合库,专为 .NET 开发人员设计,用于在其应用程序中创建、编辑和提取 PDF 文档。IronPDF 有助于 从 HTML 生成 PDFIronPDF 可用于编辑现有 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
现在,让我们创建一个静态方法,利用我们的 PdfOptions 使用 IronPDF 生成 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 起。