Zum Fußzeileninhalt springen
.NET HILFE

C# Reflection (Funktionsweise für Entwickler)

In the world of software development, C# is a versatile and powerful programming language that provides a wide range of features to developers.

One such feature that stands out for its flexibility and dynamism is reflection. Reflection in C# allows developers to inspect and interact with the metadata of types during runtime. This capability opens up a new dimension of possibilities, enabling developers to create more flexible, extensible, and robust applications.

In this article, we'll delve into the intricacies of C# reflection, exploring its key concepts, use cases, and best practices. We will also find the reflection information of the PdfDocument object of IronPDF.

Reflection in C#

Reflection is a mechanism that allows a program to examine and manipulate its structure and behavior at runtime. In C#, this is achieved through the System.Reflection namespace which provides classes and methods for interacting with metadata, obtaining information about types, and even creating instances dynamically.

Key Components of Reflection

Type Class

At the core of C# reflection is the Type class, which represents a type in the .NET runtime. This class provides a wealth of information about a type, including all the public methods, properties, fields, events, and method parameters.

You can obtain a Type object for a given type using various methods, such as the typeof() operator or by calling the GetType() method on an object.

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

Output

C# Reflection (How It Works For Developer): Figure 1

Assembly Class

An assembly in .NET is a unit of deployment and versioning. The Assembly class in the System.Reflection namespace provides methods to load and describe assemblies and inspect assembly info dynamically.

You can obtain an Assembly object for any instance of the currently executing assembly or for any referenced 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

Output

C# Reflection (How It Works For Developer): Figure 2

MethodInfo, PropertyInfo, FieldInfo, and EventInfo Classes

These classes represent public members, methods, properties, fields, and events, respectively. They expose information about these members, such as their names, types, accessibility, and more.

You can obtain access to instances of these classes through the Type class.

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

Output

C# Reflection (How It Works For Developer): Figure 3

Introducing IronPDF

IronPDF - Official Website is a powerful C# library that provides a comprehensive set of features for working with PDF documents in .NET applications. It allows developers to easily create, manipulate, and extract data from an existing object such as PDF files using a simple and intuitive API.

One notable feature of IronPDF is its ability to seamlessly integrate with existing C# projects, making it an excellent choice for adding PDF generation and manipulation capabilities.

Key Features of IronPDF

Some key features of IronPDF are as follows:

  1. PDF Generation: Easily generate PDF documents from scratch or convert HTML, images, and other formats into PDF.
  2. PDF Manipulation: Edit existing PDFs by adding, removing, or modifying text, images, and annotations.
  3. PDF Extraction: Extract text, images, and metadata from PDF files for further processing.
  4. HTML to PDF Conversion: Convert HTML content, including CSS and JavaScript, into high-quality PDFs.
  5. PDF Forms: Create and fill interactive PDF forms programmatically.
  6. Security: Apply encryption and password protection to secure PDF documents.

Now, let's explore how to use C# reflection with IronPDF in a detailed code example.

Using C# Reflection with IronPDF

In this simple example, we'll get the information about the IronPDF PDF document object using C# reflection.

Install IronPDF NuGet Package

Make sure to install the IronPDF NuGet package into your project. You can do this using the NuGet Package Manager Console:

Install-Package IronPdf

Using C# Reflection to get data of IronPDF PDF Document Object

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

The provided C# code utilizes reflection to obtain information about the PdfDocument type from the IronPDF library. Initially, the typeof(PdfDocument) expression is used to retrieve the Type object representing the PdfDocument type.

Subsequently, various properties of the obtained Type object are printed to the console, including the type name, full name, and assembly-qualified name.

Additionally, the code utilizes a foreach loop to iterate through the members of the PdfDocument type, printing information about each member, such as its member type and name.

This approach showcases the use of reflection to dynamically inspect the structure and metadata of objects of the PdfDocument type during runtime, providing insights into the composition and all the public members of the IronPDF library's PdfDocument class.

Output:

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

Conclusion

C# reflection is a powerful mechanism that empowers developers to dynamically inspect and manipulate the structure of types at runtime.

This article has explored key concepts, use cases, and best practices associated with C# reflection, highlighting its significance in creating flexible and extensible applications.

Additionally, the integration of IronPDF, a robust PDF manipulation library, further demonstrates the versatility of C# reflection in obtaining information about the PdfDocument type dynamically.

As developers leverage these capabilities, they gain the flexibility to adapt their applications to changing requirements and scenarios, showcasing the dynamic nature of C# and the valuable contributions of libraries like IronPDF in enhancing document processing capabilities.

IronPDF is a well-documented library with many tutorials. To see the tutorials, visit IronPDF Tutorial Documentation, which provides a greater opportunity for developers to learn about its features.

Häufig gestellte Fragen

Was ist C#-Reflexion und warum ist sie wichtig?

C#-Reflexion ist eine Funktion, die es Entwicklern ermöglicht, Metadaten von Typen zur Laufzeit zu inspizieren und zu manipulieren. Sie ist wichtig, da sie Flexibilität und Dynamik in der Anwendungsentwicklung bietet und es Entwicklern ermöglicht, anpassungsfähigere und erweiterbare Software zu erstellen.

Wie kann ich Reflexion verwenden, um mit PDF-Dokumenten in C# zu interagieren?

Sie können C#-Reflexion nutzen, um dynamisch Informationen über den PdfDocument-Typ in IronPDF zu erhalten. Dies ermöglicht es Ihnen, die Struktur, Komposition und öffentlichen Mitglieder der Klasse PdfDocument zur Laufzeit zu inspizieren und die dynamische Manipulation von PDF-Dokumenten zu erleichtern.

Was sind häufige Anwendungsfälle für C#-Reflexion?

Häufige Anwendungsfälle für C#-Reflexion sind die Inspektion von dynamischen Typen, die Erstellung erweiterbarer Anwendungen, der Zugriff auf Metadaten, das dynamische Laden von Assemblies und die Automatisierung der Code-Generierung. Sie erhöht die Flexibilität und Anpassungsfähigkeit der Softwareentwicklung.

Wie erleichtert die Type-Klasse die Reflexion in C#?

Die Type-Klasse in C# bietet Informationen über einen Typ, wie z. B. seine Methoden, Eigenschaften, Felder und Ereignisse. Entwickler können ein Type-Objekt mit dem typeof()-Operator oder der GetType()-Methode erhalten und es nutzen, um auf Metadaten zuzugreifen, was eine dynamische Inspektion und Interaktion mit Typen ermöglicht.

Können Sie ein Beispiel für die Verwendung von Reflexion mit IronPDF geben?

Ein Beispiel für die Verwendung von Reflexion mit IronPDF beinhaltet das Abrufen von Reflexionsinformationen für das PdfDocument-Objekt. Dies ermöglicht es Entwicklern, die Struktur und Metadaten von PDF-Dokumenten dynamisch zu inspizieren und demonstriert die Fähigkeiten von IronPDF in der PDF-Erstellung, -Manipulation und -Extraktion.

Worauf sollten Entwickler achten, wenn sie Reflexion in C# verwenden?

Wenn man Reflexion in C# verwendet, sollten Entwickler ihren Einsatz aufgrund möglicher Performance-Overheads minimieren, den sicheren Umgang mit dynamisch geladenen Typen sicherstellen und Reflexion sinnvoll in Szenarios einsetzen, in denen ihre Vorteile die Kosten überwiegen.

Wie kann die Assembly-Klasse in der C#-Reflexion genutzt werden?

Die Assembly-Klasse in System.Reflection bietet Methoden zum Laden und Inspizieren von Assemblies. Sie ermöglicht es Entwicklern, auf Metadaten von Assemblies zuzugreifen, Modulinformationen zu erkunden und Assemblies während der Laufzeit dynamisch zu laden und zu beschreiben, was das dynamische Softwaremanagement erleichtert.

Welche Vorteile bietet die Integration einer PDF-Bibliothek in C#?

Die Integration einer PDF-Bibliothek wie IronPDF in C# ermöglicht es Entwicklern, ihren Anwendungen nahtlos Funktionen zur PDF-Erstellung und -Manipulation hinzuzufügen. Sie bietet Funktionen wie PDF-Erstellung, Bearbeitung, Formularverarbeitung und Sicherheit und verbessert die Dokumentverarbeitungs-Workflows in .NET-Anwendungen.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen