.NET ヘルプ

C# リフレクション(開発者のための仕組み)

更新済み 1月 27, 2024
共有:

ソフトウェア開発の世界では、C#は開発者に幅広い機能を提供する多用途で強力なプログラミング言語です。

その柔軟性とダイナミズムで際立っている機能の一つがリフレクションです。 C#のリフレクション 開発者は実行時にタイプのメタデータを検査および操作することができます。この機能により、開発者はより柔軟で拡張性があり、堅牢なアプリケーションを作成するための新しい可能性が開かれます。

この記事では、C#リフレクションの複雑さについて掘り下げ、その主要な概念、使用例、ベストプラクティスを探ります。 以下の PdfDocument オブジェクトのリフレクション情報も見つけます。 IronPDF.

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
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の生成: HTML、画像、その他の形式をPDFに変換したり、ゼロからPDFドキュメントを簡単に生成できます。

  2. PDF操作: 既存のPDFにテキスト、画像、注釈を追加、削除、または変更します。

  3. PDF抽出: PDFファイルからテキスト、画像、およびメタデータを抽出し、さらなる処理を行います。

  4. HTMLからPDFへの変換: CSSやJavaScriptを含むHTMLコンテンツを高品質なPDFに変換します。

  5. PDFフォーム: プログラムでインタラクティブPDFフォームを作成および記入します。

  6. セキュリティ: PDFドキュメントを保護するために暗号化とパスワード保護を適用します。

    では、詳細なコード例を使って、C#リフレクションをIronPDFで使用する方法を探ってみましょう。

IronPDFでC#リフレクションを使用する

この簡単な例では、C#リフレクションを使用してIronPDF PDFドキュメントオブジェクトに関する情報を取得します。

IronPDF NuGetパッケージをインストールする

プロジェクトにIronPDF NuGetパッケージをインストールすることを忘れないでください。 これを行うには、NuGetパッケージマネージャーコンソールを使用できます:

Install-Package IronPdf

C# リフレクションを使用して IronPDF PDF ドキュメント オブジェクトのデータを取得する

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) expression は、PdfDocument 型を表す Type オブジェクトを取得するために使用されます。

その後、取得した Type オブジェクトのさまざまなプロパティがコンソールに出力されます。これには、型名、完全修飾名、およびアセンブリ修飾名が含まれます。

また、コードは foreach ループを使用して PdfDocument 型のメンバーを反復処理し、各メンバーの種類や名前などの情報を出力します。

このアプローチは、PdfDocument 型のオブジェクトの構造とメタデータを実行時に動的に検査するためにリフレクションを使用することを示しています。これにより、IronPDFライブラリの PdfDocument クラスの構成およびすべての公開メンバーについての洞察が得られます。

出力:

C#リフレクション(開発者向けの仕組み):図4

結論

C#のリフレクションは、開発者が実行時にタイプの構造を動的に調査および操作することを可能にする強力な機能です。

この記事では、C#リフレクションに関連する主要な概念、使用例、およびベストプラクティスについて探求し、柔軟で拡張性のあるアプリケーションを作成する上での重要性を強調しました。

さらに、強力なPDF操作ライブラリであるIronPDFの統合により、PdfDocument型に関する情報を動的に取得する際のC#リフレクションの柔軟性が一層示されています。

開発者がこれらの機能を活用することで、アプリケーションを変化する要件やシナリオに適応させる柔軟性を得ることができ、C#の動的な性質と、IronPDFのようなライブラリが文書処理機能を強化することに対する貴重な貢献を示すことができます。

IronPDFは、多くのチュートリアルが揃った十分に文書化されたライブラリです。 チュートリアルを見るには、アクセスしてください これ開発者が機能について学ぶ機会を増やすため。

< 以前
NPlot C#(開発者向けの使用方法)
次へ >
Npgsql C# .NET(開発者のための動作方法)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >