.NET 幫助

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

發佈 2024年1月27日
分享:

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

其中一個因其靈活性和動態性而脫穎而出的功能是反射。 C# 中的反射 允許開發人員在運行時檢查和交互類型的元數據。這種能力開啟了新的可能性,使開發人員能夠創建更靈活、可擴展和健壯的應用程序。

在本文中,我們將深入探討C#反射的複雜性,探索其關鍵概念、使用案例和最佳實踐。我們還將找到PdfDocument對象的反射信息。 IronPDF.

C#中的反射

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

反射的關鍵組成部分

Type 類別

在 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
VB   C#

輸出

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
VB   C#

輸出

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
VB   C#

輸出

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 Package

確保將 IronPDF NuGet 套件安裝到您的專案中。您可以使用 NuGet Package Manager Console 來完成此操作:

Install-Package IronPdf

使用 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
VB   C#

提供的 C# 程式碼使用反射來取得有關 IronPDF 庫中 PdfDocument 類型的資訊。最初,typeof(PdfDocument)```html 表達式用來取得代表 PdfDocument 類型的 Type 物件。

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

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

這種方法展示了在運行時利用 reflection 動態檢查 PdfDocument 類型的物件結構和元數據,提供了 IronPDF 函式庫中 PdfDocument 類的組成和所有公共成員的見解。

輸出:



![C# 反射(對開發人員的工作原理):圖 4](/static-assets/pdf/blog/csharp-reflection/csharp-reflection-4.webp)

### 結論

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

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

此外,本文還展示了結合使用 IronPDF(一個強大的 PDF 操作庫),如何進一步展示 C# 反射在動態獲取 **PdfDocument** 類型信息中的多樣性。

隨著開發人員利用這些功能,他們可以靈活地使應用程序適應不斷變化的需求和場景,展示了 C# 的動態特性以及像 IronPDF 這樣的庫在增強文檔處理能力中的重要貢獻。

IronPDF 是一個有良好文檔記錄的庫,其中包含許多有關如何使用 IronPDF 的教程。要查看這些教程,請訪問 [這裡](trial-license),這為開發者提供了一個更大的機會來了解其功能。
< 上一頁
NPlot C# (如何為開發者工作)
下一個 >
Npgsql C# .NET(開發人員如何使用)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >