跳過到頁腳內容
.NET幫助

C# 反射(對於開發者的運行原理)

在軟體開發的世界裡,C# 是一種多功能且功能強大的程式語言,提供開發人員多樣的功能。

其中一個以靈活性和動態性最為突出的功能就是反射。 C#中的反射允許開發人員在執行期間檢查類型的元資料並與之互動。這項功能開啟了新的可能性層面,使開發人員能夠建立更靈活、可擴充且更穩健的應用程式。

在這篇文章中,我們將深入探討 C# 反射的複雜性,探索其主要概念、使用案例和最佳實務。 我們也會找到 IronPDFPdfDocument 物件的反射資訊。

C# 中的反射;

反射(Reflection)是一種機制,允許程式在執行時檢查並操縱其結構與行為。在 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# Reflection (How It Works For Developer):圖 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# Reflection (How It Works For Developer):圖 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# Reflection (How It Works For Developer):圖 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 轉換: 將 HTML 內容(包括 CSS 和 JavaScript)轉換為高品質的 PDF。 5.PDF 表單: 以程式化方式建立和填寫互動式 PDF 表單。 6.安全性:應用加密和密碼保護來保護 PDF 文件。

現在,讓我們在詳細的程式碼範例中探討如何使用 IronPDF 的 C# 反射。

使用 IronPDF 的 C# 反射。

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

安裝 IronPDF NuGet 套件。

請務必安裝 IronPDF NuGet 套件到您的專案中。 您可以使用 NuGet Package Manager Console 進行此工作:

Install-Package IronPdf

使用 C# Reflection 取得 IronPDF PDF 文件物件的資料。

using IronPdf;
using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        // Get the Type object representing PdfDocument
        Type pdfDocumentType = typeof(PdfDocument);

        // Display basic information about the PdfDocument type
        Console.WriteLine("Information about the PdfDocument type:");
        Console.WriteLine($"Type Name: {pdfDocumentType.Name}");
        Console.WriteLine($"Full Name: {pdfDocumentType.FullName}");
        Console.WriteLine($"Assembly Qualified Name: {pdfDocumentType.AssemblyQualifiedName}");
        Console.WriteLine("\nMembers:");

        // Iterate over all members and display their information
        foreach (var memberInfo in pdfDocumentType.GetMembers())
        {
            Console.WriteLine($"{memberInfo.MemberType} {memberInfo.Name}");
        }
    }
}
using IronPdf;
using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        // Get the Type object representing PdfDocument
        Type pdfDocumentType = typeof(PdfDocument);

        // Display basic information about the PdfDocument type
        Console.WriteLine("Information about the PdfDocument type:");
        Console.WriteLine($"Type Name: {pdfDocumentType.Name}");
        Console.WriteLine($"Full Name: {pdfDocumentType.FullName}");
        Console.WriteLine($"Assembly Qualified Name: {pdfDocumentType.AssemblyQualifiedName}");
        Console.WriteLine("\nMembers:");

        // Iterate over all members and display their information
        foreach (var memberInfo in pdfDocumentType.GetMembers())
        {
            Console.WriteLine($"{memberInfo.MemberType} {memberInfo.Name}");
        }
    }
}
Imports Microsoft.VisualBasic
Imports IronPdf
Imports System
Imports System.Reflection

Friend Class Program
	Shared Sub Main()
		' Get the Type object representing PdfDocument
		Dim pdfDocumentType As Type = GetType(PdfDocument)

		' Display basic information about the PdfDocument type
		Console.WriteLine("Information about the PdfDocument type:")
		Console.WriteLine($"Type Name: {pdfDocumentType.Name}")
		Console.WriteLine($"Full Name: {pdfDocumentType.FullName}")
		Console.WriteLine($"Assembly Qualified Name: {pdfDocumentType.AssemblyQualifiedName}")
		Console.WriteLine(vbLf & "Members:")

		' Iterate over all members and display their information
		For Each memberInfo In pdfDocumentType.GetMembers()
			Console.WriteLine($"{memberInfo.MemberType} {memberInfo.Name}")
		Next memberInfo
	End Sub
End Class
$vbLabelText   $csharpLabel

所提供的 C# 程式碼利用反射從 IronPDF 函式庫取得 PdfDocument 類型的相關資訊。 最初,typeof(PdfDocument) 表達式用於擷取代表 PdfDocument 類型的 Type 物件。

隨後,會將取得的 Type 物件的各種屬性列印到控制台,包括類型名稱、全名和程序集限定名稱。

此外,程式碼利用 foreach 循環來遍歷 PdfDocument 類型的成員,列印每個成員的相關資訊,例如其成員類型和名稱。

本方法展示了使用反射在運行期間動態檢查 PdfDocument 類型物件的結構和元資料,提供對 IronPDF 函式庫的 PdfDocument 類的組成和所有公共成員的深入瞭解。

Output:

C# Reflection (How It Works For Developer):圖 4

結論

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

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

此外,整合了 IronPDF 這個強大的 PDF 操作函式庫,進一步展示了 C# 反映在動態取得 PdfDocument 類型資訊方面的多功能性。

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

IronPDF 是一個文件完備的函式庫,有許多教學。 如需查看教程,請造訪 IronPDF 教程文件,它為開發人員提供了更多了解其功能的機會。

常見問題解答

什麼是 C# 反射,為什麼它很重要?

C# 反射是一種允許開發人員在執行期間檢查和操作類型的元資料的功能。它之所以重要,是因為它提供應用程式開發的彈性與動態性,使開發人員能建立更具適應性與擴充性的軟體。

如何在 C# 中使用反射與 PDF 文件互動?

您可以使用 C# 反射動態取得 IronPDF 中 PdfDocument 類型的相關資訊。這可讓您在執行時檢查 PdfDocument 類的結構、組成和公共成員,方便您動態操作 PDF 文件。

C# 反射有哪些常見用例?

C# 反射的常見用例包括動態類型檢查、建立可擴充的應用程式、存取元資料、動態載入程式集,以及自動化程式碼產生。它增強了軟體開發的彈性和適應性。

Type 類如何促進 C# 中的反射?

C# 中的 Type 類提供類型的相關資訊,例如其方法、屬性、欄位和事件。開發人員可以使用 typeof() 運算子或 GetType() 方法取得 Type 物件,並使用它存取元資料,以實現與類型的動態檢驗和互動。

您能提供一個使用 IronPDF 反射的範例嗎?

在 IronPDF 中使用反射的一個示例涉及獲取 PdfDocument 物件的反射資訊。這允許開發人員動態檢查 PDF 文件的結構和元資料,展示了 IronPDF 在 PDF 生成、操作和提取方面的能力。

開發人員在 C# 中使用反射時應注意哪些事項?

在 C# 中使用反射時,開發人員應考慮因潛在的性能開銷而盡量減少其使用,確保安全處理動態載入的類型,並在反射的優點超過其成本的情況下明智地使用反射。

如何在 C# 反射中利用組合類?

System.Reflection 中的 Assembly 類提供載入和檢查程序集的方法。它允許開發人員存取程序集元資料、探索模組資訊,以及在執行期間動態載入和描述程序集,促進動態軟體管理。

將 PDF 函式庫與 C# 整合有哪些優點?

將 IronPDF 之類的 PDF 函式庫與 C# 整合,可讓開發人員在應用程式中無縫新增 PDF 產生與處理功能。它提供了 PDF 創建、編輯、表單處理和安全性等功能,增強了 .NET 應用程式中的文件處理工作流程。

Jacob Mellor, Team Iron 首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。