.NET 幫助

C# 反射(開發人員如何使用)

在軟體開發的世界中,C# 是一種多功能且強大的程式語言,為開發者提供了廣泛的功能。

其中一個以靈活性和動態性著稱的功能是反射。 C# 的反射允許開發人員在運行時檢查和操作類型的元數據。這項功能開啟了新的可能性,使開發人員能夠創建更具靈活性、可擴展性和穩健性的應用程式。

在本文中,我們將深入探討 C# 反射的複雜性,探索其關鍵概念、用例和最佳實踐。 我們還將尋找IronPDFPdfDocument物件的反射資訊。

C#中的反射

反射是一種機制,允許程式在執行時檢查和操縱其結構及行為。在 C# 中,這是通過 System.Reflection 命名空間實現的,該命名空間提供類別和方法以便與中繼資料互動、獲取類型資訊,甚至動態創建實例。

反射的關鍵組成部分

類型類別

C# 反射的核心是 Type 類別,這表示 .NET 執行階段中的一個類型。此類別提供有關類型的大量資訊,包括所有的公共方法、屬性、欄位、事件及方法參數。

您可以通過各種方法獲取給定類型的Type對象,例如使用typeof()運算符或在對象上調用GetType()方法。

using System;

class Program
{
    static void Main()
    {
        // Using typeof to get Type information for string
        Type stringType = typeof(string);
        Console.WriteLine("Information about the string type:");
        Console.WriteLine($"Type Name: {stringType.Name}");
        Console.WriteLine($"Full Name: {stringType.FullName}");
        Console.WriteLine($"Assembly Qualified Name: {stringType.AssemblyQualifiedName}");
    }
}
using System;

class Program
{
    static void Main()
    {
        // Using typeof to get Type information for string
        Type stringType = typeof(string);
        Console.WriteLine("Information about the string type:");
        Console.WriteLine($"Type Name: {stringType.Name}");
        Console.WriteLine($"Full Name: {stringType.FullName}");
        Console.WriteLine($"Assembly Qualified Name: {stringType.AssemblyQualifiedName}");
    }
}
Imports System

Friend Class Program
	Shared Sub Main()
		' Using typeof to get Type information for string
		Dim stringType As Type = GetType(String)
		Console.WriteLine("Information about the string type:")
		Console.WriteLine($"Type Name: {stringType.Name}")
		Console.WriteLine($"Full Name: {stringType.FullName}")
		Console.WriteLine($"Assembly Qualified Name: {stringType.AssemblyQualifiedName}")
	End Sub
End Class
$vbLabelText   $csharpLabel

輸出

C# 反射(開發人員工作原理):圖 1

程序集類別

在 .NET 中,程式集是部署和版本控制的單位。 System.Reflection 命名空間中的 Assembly 類別提供了載入和描述組件以及動態檢查組件資訊的方法。

您可以為當前執行的程式集或任何引用的程式集的實例獲取一個Assembly對象。

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        // Example 1: Get information about the executing assembly
        Assembly executingAssembly = Assembly.GetExecutingAssembly();
        Console.WriteLine("Information about the executing assembly:");
        DisplayAssemblyInfo(executingAssembly);

        // Example 2: Load the mscorlib assembly
        Assembly mscorlibAssembly = Assembly.Load("mscorlib");
        Console.WriteLine("\nInformation about the mscorlib assembly:");
        DisplayAssemblyInfo(mscorlibAssembly);
    }

    static void DisplayAssemblyInfo(Assembly assembly)
    {
        Console.WriteLine($"Assembly Name: {assembly.GetName().Name}");
        Console.WriteLine($"Full Name: {assembly.FullName}");
        Console.WriteLine($"Location: {assembly.Location}");
        Console.WriteLine("\nModules:");

        foreach (var module in assembly.GetModules())
        {
            Console.WriteLine($"- {module.Name}");
        }

        Console.WriteLine(new string('-', 30));
    }
}
using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        // Example 1: Get information about the executing assembly
        Assembly executingAssembly = Assembly.GetExecutingAssembly();
        Console.WriteLine("Information about the executing assembly:");
        DisplayAssemblyInfo(executingAssembly);

        // Example 2: Load the mscorlib assembly
        Assembly mscorlibAssembly = Assembly.Load("mscorlib");
        Console.WriteLine("\nInformation about the mscorlib assembly:");
        DisplayAssemblyInfo(mscorlibAssembly);
    }

    static void DisplayAssemblyInfo(Assembly assembly)
    {
        Console.WriteLine($"Assembly Name: {assembly.GetName().Name}");
        Console.WriteLine($"Full Name: {assembly.FullName}");
        Console.WriteLine($"Location: {assembly.Location}");
        Console.WriteLine("\nModules:");

        foreach (var module in assembly.GetModules())
        {
            Console.WriteLine($"- {module.Name}");
        }

        Console.WriteLine(new string('-', 30));
    }
}
Imports Microsoft.VisualBasic
Imports System
Imports System.Reflection

Friend Class Program
	Shared Sub Main()
		' Example 1: Get information about the executing assembly
		Dim executingAssembly As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()
		Console.WriteLine("Information about the executing assembly:")
		DisplayAssemblyInfo(executingAssembly)

		' Example 2: Load the mscorlib assembly
		Dim mscorlibAssembly As System.Reflection.Assembly = System.Reflection.Assembly.Load("mscorlib")
		Console.WriteLine(vbLf & "Information about the mscorlib assembly:")
		DisplayAssemblyInfo(mscorlibAssembly)
	End Sub

	Private Shared Sub DisplayAssemblyInfo(ByVal assembly As System.Reflection.Assembly)
		Console.WriteLine($"Assembly Name: {assembly.GetName().Name}")
		Console.WriteLine($"Full Name: {assembly.FullName}")
		Console.WriteLine($"Location: {assembly.Location}")
		Console.WriteLine(vbLf & "Modules:")

		For Each [module] In assembly.GetModules()
			Console.WriteLine($"- {[module].Name}")
		Next [module]

		Console.WriteLine(New String("-"c, 30))
	End Sub
End Class
$vbLabelText   $csharpLabel

輸出

C# 反射(對開發人員的工作原理):圖2

MethodInfo、PropertyInfo、FieldInfo 和 EventInfo 類別

這些類分別表示公共成員、方法、屬性、欄位和事件。 他們公開了有關這些成員的資訊,例如他們的名稱、類型、可存取性等。

您可以透過Type類別獲得這些類別的實例訪問權限。

using System;
using System.Reflection;

class MyClass
{
    public void MyMethod() { }
    public int MyProperty { get; set; }
    public string myField;
    public event EventHandler MyEvent;
}

class Program
{
    static void Main()
    {
        // Get MethodInfo for MyMethod
        MethodInfo methodInfo = typeof(MyClass).GetMethod("MyMethod");
        Console.WriteLine($"Method Name: {methodInfo.Name}");

        // Get PropertyInfo for MyProperty
        PropertyInfo propertyInfo = typeof(MyClass).GetProperty("MyProperty");
        Console.WriteLine($"Property Name: {propertyInfo.Name}");

        // Get FieldInfo for myField
        FieldInfo fieldInfo = typeof(MyClass).GetField("myField");
        Console.WriteLine($"Field Name: {fieldInfo.Name}");

        // Get EventInfo for MyEvent
        EventInfo eventInfo = typeof(MyClass).GetEvent("MyEvent");
        Console.WriteLine($"Event Name: {eventInfo.Name}");
    }
}
using System;
using System.Reflection;

class MyClass
{
    public void MyMethod() { }
    public int MyProperty { get; set; }
    public string myField;
    public event EventHandler MyEvent;
}

class Program
{
    static void Main()
    {
        // Get MethodInfo for MyMethod
        MethodInfo methodInfo = typeof(MyClass).GetMethod("MyMethod");
        Console.WriteLine($"Method Name: {methodInfo.Name}");

        // Get PropertyInfo for MyProperty
        PropertyInfo propertyInfo = typeof(MyClass).GetProperty("MyProperty");
        Console.WriteLine($"Property Name: {propertyInfo.Name}");

        // Get FieldInfo for myField
        FieldInfo fieldInfo = typeof(MyClass).GetField("myField");
        Console.WriteLine($"Field Name: {fieldInfo.Name}");

        // Get EventInfo for MyEvent
        EventInfo eventInfo = typeof(MyClass).GetEvent("MyEvent");
        Console.WriteLine($"Event Name: {eventInfo.Name}");
    }
}
Imports System
Imports System.Reflection

Friend Class [MyClass]
	Public Sub MyMethod()
	End Sub
	Public Property MyProperty() As Integer
	Public myField As String
	Public Event MyEvent As EventHandler
End Class

Friend Class Program
	Shared Sub Main()
		' Get MethodInfo for MyMethod
		Dim methodInfo As MethodInfo = GetType([MyClass]).GetMethod("MyMethod")
		Console.WriteLine($"Method Name: {methodInfo.Name}")

		' Get PropertyInfo for MyProperty
		Dim propertyInfo As PropertyInfo = GetType([MyClass]).GetProperty("MyProperty")
		Console.WriteLine($"Property Name: {propertyInfo.Name}")

		' Get FieldInfo for myField
		Dim fieldInfo As FieldInfo = GetType([MyClass]).GetField("myField")
		Console.WriteLine($"Field Name: {fieldInfo.Name}")

		' Get EventInfo for MyEvent
		Dim eventInfo As EventInfo = GetType([MyClass]).GetEvent("MyEvent")
		Console.WriteLine($"Event Name: {eventInfo.Name}")
	End Sub
End Class
$vbLabelText   $csharpLabel

輸出

C# 反射(開發人員如何使用):圖 3

介紹 IronPDF

IronPDF - 官方網站 是一個強大的 C# 程式庫,為 .NET 應用程式提供了一套完整的功能,用於處理 PDF 文件。 它讓開發者能夠輕鬆地使用簡單直觀的 API 來創建、操作和提取現有物件中的數據,例如 PDF 文件。

IronPDF 的一個顯著功能是能夠無縫整合到現有的 C# 專案中,使其成為新增 PDF 生成和操作功能的絕佳選擇。

IronPDF 的主要功能

IronPDF的一些主要功能如下:

  1. PDF 生成:輕鬆從頭開始生成 PDF 文件,或將 HTML、圖片及其他格式轉換為 PDF。

  2. PDF 操作:通過添加、移除或修改文本、圖像和註解來編輯現有的 PDF。

  3. PDF 提取:從 PDF 文件中提取文本、圖像和元數據以進行進一步處理。

  4. HTML 轉換為 PDF:將包含 CSS 和 JavaScript 的 HTML 內容轉換為高品質的 PDF。

  5. PDF 表單:以程式設計方式創建和填寫互動式 PDF 表單。

  6. 安全性:應用加密和密碼保護,以保護 PDF 文件的安全。

    現在,讓我們通過詳細的代碼範例來探索如何在 C# 中使用反射與 IronPDF。

使用 C# 反射與 IronPDF

在這個簡單的範例中,我們將使用 C# 反射來獲取 IronPDF PDF 文件對象的資訊。

安裝 IronPDF NuGet 套件

請確保將 IronPDF NuGet 套件安裝到您的專案中。 您可以使用 NuGet 套件管理器控制台來執行此操作:

Install-Package IronPdf
Install-Package IronPdf
SHELL

使用 C# Reflection 獲取 IronPDF PDF Document Object 的數據

using IronPdf;
using System;

Type PDF = typeof(PdfDocument);
Console.WriteLine("Information about the PdfDocument type:");
Console.WriteLine($"Type Name: {PDF.Name}");
Console.WriteLine($"Full Name: {PDF.FullName}");
Console.WriteLine($"Assembly Qualified Name: {PDF.AssemblyQualifiedName}");
Console.WriteLine("\nMembers:");
foreach (var memberInfo in PDF.GetMembers())
{
    Console.WriteLine($"{memberInfo.MemberType} {memberInfo.Name}");
}
using IronPdf;
using System;

Type PDF = typeof(PdfDocument);
Console.WriteLine("Information about the PdfDocument type:");
Console.WriteLine($"Type Name: {PDF.Name}");
Console.WriteLine($"Full Name: {PDF.FullName}");
Console.WriteLine($"Assembly Qualified Name: {PDF.AssemblyQualifiedName}");
Console.WriteLine("\nMembers:");
foreach (var memberInfo in PDF.GetMembers())
{
    Console.WriteLine($"{memberInfo.MemberType} {memberInfo.Name}");
}
Imports Microsoft.VisualBasic
Imports IronPdf
Imports System

Private PDF As Type = GetType(PdfDocument)
Console.WriteLine("Information about the PdfDocument type:")
Console.WriteLine($"Type Name: {PDF.Name}")
Console.WriteLine($"Full Name: {PDF.FullName}")
Console.WriteLine($"Assembly Qualified Name: {PDF.AssemblyQualifiedName}")
Console.WriteLine(vbLf & "Members:")
For Each memberInfo In PDF.GetMembers()
	Console.WriteLine($"{memberInfo.MemberType} {memberInfo.Name}")
Next memberInfo
$vbLabelText   $csharpLabel

提供的 C# 代碼使用反射從 IronPDF 庫中獲取有關 PdfDocument 類型的信息。 最初,typeof(PdfDocument) 表達式用於檢索表示 PdfDocument 類型的 Type 對象。

隨後,取得的Type物件的各種屬性將被列印到控制台,包括類型名稱、完整名稱和組件限定名稱。

此外,代碼使用foreach迴圈來遍歷PdfDocument類型的成員,並打印每個成員的信息,例如其成員類型和名稱。

此方法展示了如何使用反射在運行時動態檢查 PdfDocument 類型物件的結構和元數據,從而深入了解 IronPDF 庫的 PdfDocument 類的組成及所有公共成員。

輸出:

C# Reflection(開發人員如何使用):圖 4

結論

C# 反射是一種強大的機制,使開發人員能夠在運行時動態檢查和操作類型的結構。

本文探討了與 C# 反射相關的關鍵概念、使用案例和最佳實踐,強調了其在創建靈活且可擴展應用程式中的重要性。

此外,集成了 IronPDF,一個強大的 PDF 操作庫,進一步展示了 C# 反射在動態獲取 PdfDocument 類型信息方面的多樣性。

當開發人員利用這些功能時,他們可以靈活地調整其應用程式以適應不斷變化的要求和情境,展現了C#的動態特性,以及像IronPDF這樣的庫在增強文件處理能力方面的寶貴貢獻。

IronPDF 是一個有良好文件記錄的函式庫,並提供許多教學。 要查看教程,請訪問IronPDF 教程文檔,這為開發人員提供了更大的學習其功能的機會。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
NPlot C# (如何為開發者工作)
下一個 >
Npgsql C# .NET(開發人員如何使用)