.NET ヘルプ

C# 属性(開発者向けの使い方)

更新済み 2月 18, 2024
共有:

C#プログラミングの世界では、メタデータがコードのセマンティクスや動作を充実させる重要な役割を果たします。 C#属性 さまざまなエンティティにメタデータを付与するための強力なツールとして登場し、これによりコンパイラ、ツール、および実行環境がそれらのエンティティを解釈し相互作用する方法が形成されます。

この包括的なガイドでは、C#の属性について、その構文、用途、そしてコードの表現力と機能性を向上させるための多用途なメカニズムとしてどのように機能するかを探ります。

C#属性の基本を理解する: 入門編

アトリビュート(属性)は、角括弧によって示されます。 (もちろん、英語のテキストを教えていただけますでしょうか?[]もちろん、英語のテキストを教えていただけますでしょうか?), はコード要素の上に配置され、それらに関する追加情報を提供する宣言的タグです。 この追加情報、メタデータとしても知られているものは、コードの基本的な機能には影響を与えませんが、コンパイラ、ランタイム環境、およびツールにとって貴重な洞察を提供します。

C#では、オブジェクト属性はクラスやメソッドのようなプログラムエンティティに関連付けられたメタデータを表します。 属性構文を使用して定義される属性インスタンスは、Conditionalの使用など、プログラムエンティティの説明を強化します。(「デバッグ」)条件付きでコードを含めるために ` を使用します。

以下はC#で属性を使用する基本的な例です:

[Serializable]
public class Person
{
    // Class Implementation
}
[Serializable]
public class Person
{
    // Class Implementation
}
<Serializable>
Public Class Person
	' Class Implementation
End Class
VB   C#

この例では、Serializable 属性は Person クラスのインスタンスがシリアル化可能であることを示しています。

C# 属性の種類

C# コードのさまざまな要素に属性が適用されます。 含まれるのは:

  1. アセンブリ: アセンブリ全体に適用され、コンパイルおよび実行時の動作に影響を与えます。
    [assembly: AssemblyVersion("1.0.0.0")]
    [assembly: AssemblyVersion("1.0.0.0")]
<Assembly: AssemblyVersion("1.0.0.0")>
VB   C#
  1. モジュール: アセンブリ内のモジュールに適用され、モジュール自体に関する情報を提供します。
    [module: SomeCustomModuleAttribute]
    [module: SomeCustomModuleAttribute]
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#
  1. タイプ: 型に適用され、その動作に影響を与えたり、追加情報を提供したりします。
    [Serializable]
        public class Person
        {
            // Class Implementation
        }
    [Serializable]
        public class Person
        {
            // Class Implementation
        }
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#
  1. メソッド: メソッドに適用され、その動作を変えたりツールに情報を提供します。
    [Obsolete("Use the newMethod instead.")]
        public void DeprecatedMethod()
        {
            // Method implementation
        }
    [Obsolete("Use the newMethod instead.")]
        public void DeprecatedMethod()
        {
            // Method implementation
        }
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#
  1. プロパティ、フィールド、イベントなど: 型内の特定のメンバーに適用され、それらのメンバーに関連するメタデータを提供します。
    public class Example
        {
            [DefaultValue(42)]
            public int Answer { get; set; }
        }
    public class Example
        {
            [DefaultValue(42)]
            public int Answer { get; set; }
        }
Public Class Example
			<DefaultValue(42)>
			Public Property Answer() As Integer
End Class
VB   C#

C#でカスタム属性を作成する

C#には多くの組み込み属性が用意されていますが、開発者はカスタム属性を作成してコードに関する特定の情報を伝えることができます。 カスタム属性は、System.Attributeから継承するクラスを作成することによって定義されます。

[AttributeUsage(AttributeTargets.Class 
 AttributeTargets.Method, AllowMultiple = true)]
public class CustomAttribute : Attribute
{
    // Attribute Implementation
}
[AttributeUsage(AttributeTargets.Class 
 AttributeTargets.Method, AllowMultiple = true)]
public class CustomAttribute : Attribute
{
    // Attribute Implementation
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

この例では、CustomAttribute はクラスやメソッドに適用でき、AllowMultiple プロパティは単一のターゲットに複数の属性のインスタンスを許可するかどうかを指定します。 カスタム属性クラスを作成する際に、通常のクラスと区別するためにクラス名に属性サフィックスが追加されます。 属性コンストラクタはこれらのプロパティを初期化し、位置パラメータはこれらの属性に値を渡す役割を果たし、コードに構造化された情報を提供します。

C# アトリビュートの応用

コードドキュメント

属性は、コードの文書化および開発者やツールに追加情報を提供する上で重要な役割を果たします。 たとえば、[廃止された] 属性は特定の要素が使用されなくなったことを示しており、開発者は代替手段に移行する必要があります。

[Obsolete("This method is obsolete. Use the newMethod instead.")]
public void DeprecatedMethod()
{
    // Method Implementation
}
[Obsolete("This method is obsolete. Use the newMethod instead.")]
public void DeprecatedMethod()
{
    // Method Implementation
}
<Obsolete("This method is obsolete. Use the newMethod instead.")>
Public Sub DeprecatedMethod()
	' Method Implementation
End Sub
VB   C#

2. シリアル化および永続化

属性のような**[シリアライズ可能]型のインスタンスがシリアライズ可能であることをランタイム環境に通知します。 データ永続性のシナリオを扱う際には、これは非常に重要です。

[Serializable]
public class Person
{
    // Class implementation
}
[Serializable]
public class Person
{
    // Class implementation
}
<Serializable>
Public Class Person
	' Class implementation
End Class
VB   C#

コード分析とツール統合

属性は、静的解析およびコード生成ツールに貢献します。 例えば、ユニットテストフレームワークのようなツールは、TestMethodのような属性を使用してテストメソッドを識別します。

[TestClass]
public class MyTestClass
{
    [TestMethod]
    public void TestMethod()
    {
        // Test method implementation
    }
}
[TestClass]
public class MyTestClass
{
    [TestMethod]
    public void TestMethod()
    {
        // Test method implementation
    }
}
<TestClass>
Public Class MyTestClass
	<TestMethod>
	Public Sub TestMethod()
		' Test method implementation
	End Sub
End Class
VB   C#

ASP.NET MVC ルーティング

ASP.NET MVCでは、属性はルーティングに広く使用されています。 Route 属性は、開発者がアクションメソッドのルートテンプレートを指定することを可能にします。

[Route("api/[controller]")]
public class SampleController : Controller
{
    [HttpGet]
    [Route("GetSampleData")]
    public IActionResult GetSampleData()
    {
        // Action method implementation
    }
}
[Route("api/[controller]")]
public class SampleController : Controller
{
    [HttpGet]
    [Route("GetSampleData")]
    public IActionResult GetSampleData()
    {
        // Action method implementation
    }
}
<Route("api/[controller]")>
Public Class SampleController
	Inherits Controller

	<HttpGet>
	<Route("GetSampleData")>
	Public Function GetSampleData() As IActionResult
		' Action method implementation
	End Function
End Class
VB   C#

IronPDFの紹介:概要

IronPDF C# .NET Framework開発者向けに設計された多用途なライブラリであり、PDFの生成と操作に関する幅広いツールを提供します。 HTMLからPDFを作成することから、既存のドキュメントからコンテンツを抽出することまで、IronPDFは複雑なタスクを簡略化し、開発者のツールキットに貴重な資産を提供します。

C#属性(開発者向けの動作方法): 図1 - IronPDFウェブページ

IronPDFのインストール: クイックスタート

C#プロジェクトでIronPDFライブラリを活用するためには、IronPDFのNuGetパッケージを簡単にインストールできます。 次のコマンドをパッケージ マネージャー コンソールで使用してください:

Install-Package IronPdf

または、NuGetパッケージマネージャーで「IronPDF」を検索し、そこからインストールすることもできます。

C# 属性: クイック概要

C#の属性は、クラス、メソッド、プロパティなどのコード内のエンティティに追加情報を提供する宣言的なタグです。 それらは、上記のように、開発者がコードの中核的な機能を変更することなく、メタデータを添付したり振る舞いを定義したりすることを可能にします。 IronPDFの属性統合を探求していく中で、PDF生成に対するより微妙なアプローチにどのように寄与するかについて発見することができます。

C#属性によるPDF生成の強化

ドキュメントメタデータのカスタマイズ

属性を利用して、PDFドキュメントに関連するメタデータを強化することができます。 IronPDFを使用すると、開発者はタイトル、作成者、件名などのメタデータ要素をカスタマイズできます。 属性を使用することで、生成されたPDFに動的にこの情報を挿入することができます。 以下の例は、IronPDFで異なる属性クラスを使用する方法を示しています:

PdfGenerationWithAttributes obj = new PdfGenerationWithAttributes();
obj.GeneratePdf();
// Define the DocumentMetadataAttribute
public class DocumentMetadataAttribute : Attribute
{
    public string Title { get; set; }
    public string Author { get; set; }
    public string Subject { get; set; }
}
[DocumentMetadata(Title = "Custom PDF Title", Author = "John Doe", Subject = "Document Subject")]
public class PdfGenerationWithAttributes
{
    public void GeneratePdf()
    {
        // Instantiate IronPDF PdfDocument
        var pdfDocument = new PdfDocument("StyledDocument.pdf");
        // Retrieve DocumentMetadataAttribute using reflection
        var documentMetadata = typeof(PdfGenerationWithAttributes)
            .GetCustomAttributes(typeof(DocumentMetadataAttribute), false)
            .FirstOrDefault() as DocumentMetadataAttribute;
        // Set metadata values
        pdfDocument.MetaData.Title = documentMetadata?.Title;
        pdfDocument.MetaData.Author = documentMetadata?.Author;
        pdfDocument.MetaData.Subject = documentMetadata?.Subject;
        // Perform document generation
        pdfDocument.SaveAs("CustomizedDocument.pdf");
    }
}
PdfGenerationWithAttributes obj = new PdfGenerationWithAttributes();
obj.GeneratePdf();
// Define the DocumentMetadataAttribute
public class DocumentMetadataAttribute : Attribute
{
    public string Title { get; set; }
    public string Author { get; set; }
    public string Subject { get; set; }
}
[DocumentMetadata(Title = "Custom PDF Title", Author = "John Doe", Subject = "Document Subject")]
public class PdfGenerationWithAttributes
{
    public void GeneratePdf()
    {
        // Instantiate IronPDF PdfDocument
        var pdfDocument = new PdfDocument("StyledDocument.pdf");
        // Retrieve DocumentMetadataAttribute using reflection
        var documentMetadata = typeof(PdfGenerationWithAttributes)
            .GetCustomAttributes(typeof(DocumentMetadataAttribute), false)
            .FirstOrDefault() as DocumentMetadataAttribute;
        // Set metadata values
        pdfDocument.MetaData.Title = documentMetadata?.Title;
        pdfDocument.MetaData.Author = documentMetadata?.Author;
        pdfDocument.MetaData.Subject = documentMetadata?.Subject;
        // Perform document generation
        pdfDocument.SaveAs("CustomizedDocument.pdf");
    }
}
Private obj As New PdfGenerationWithAttributes()
obj.GeneratePdf()
' Define the DocumentMetadataAttribute
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'public class DocumentMetadataAttribute : Attribute
'{
'	public string Title
'	{
'		get;
'		set;
'	}
'	public string Author
'	{
'		get;
'		set;
'	}
'	public string Subject
'	{
'		get;
'		set;
'	}
'}
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'[DocumentMetadata(Title = "Custom PDF Title", Author = "John Doe", Subject = "Document Subject")]
'public class PdfGenerationWithAttributes
'{
'	public void GeneratePdf()
'	{
'		' Instantiate IronPDF PdfDocument
'		var pdfDocument = New PdfDocument("StyledDocument.pdf");
'		' Retrieve DocumentMetadataAttribute using reflection
'		var documentMetadata = TryCast(typeof(PdfGenerationWithAttributes).GetCustomAttributes(typeof(DocumentMetadataAttribute), False).FirstOrDefault(), DocumentMetadataAttribute);
'		' Set metadata values
'		pdfDocument.MetaData.Title = If(documentMetadata Is Nothing, Nothing, documentMetadata.Title);
'		pdfDocument.MetaData.Author = If(documentMetadata Is Nothing, Nothing, documentMetadata.Author);
'		pdfDocument.MetaData.Subject = If(documentMetadata Is Nothing, Nothing, documentMetadata.Subject);
'		' Perform document generation
'		pdfDocument.SaveAs("CustomizedDocument.pdf");
'	}
'}
VB   C#

この例では、DocumentMetadataAttribute はメタデータ情報を伝えるためのカスタム属性として機能し、PDF生成時の動的なカスタマイズを可能にします。 提供されたコードは、C#で DocumentMetadataAttribute という名前のカスタム属性クラスを定義しています。 属性は、クラス、メソッド、プロパティなどのプログラムエンティティにメタデータや宣言的情報を追加するための方法です。 これらの属性は、リフレクションを介してPDFドキュメントのMetaDataを編集するために使用されます。

C# 属性(開発者のためのしくみ):図2 - 「ドキュメントプロパティ」を通じて出力されたPDFのメタデータを見る

属性を使用したPDFレイアウトの制御

属性を使用してPDFドキュメントのレイアウトを制御することもできます。 IronPDFは、ページサイズ、余白、および向きを設定するオプションを提供します。 属性を使用することによって、特定の要件に基づいてこれらのレイアウト設定をパラメータ化できます。

[PageLayout(Size = IronPdf.Rendering.PdfPaperSize.A4, MarginTop = 20, MarginBottom = 20, MarginLeft = 10, MarginRight = 10)]
public class PdfGenerationWithLayoutAttributes
{
    public void GeneratePdf()
    {
        // Instantiate IronPDF PdfDocument
        var pdfDocument = new ChromePdfRenderer();
        // Retrieve PageLayoutAttribute using reflection
        var pageLayout = typeof(PdfGenerationWithLayoutAttributes)
            .GetCustomAttributes(typeof(PageLayoutAttribute), false)
            .FirstOrDefault() as PageLayoutAttribute;
        // Set layout values
        pdfDocument.RenderingOptions.PaperSize = pageLayout?.Size;
        pdfDocument.RenderingOptions.MarginTop = pageLayout?.MarginTop ?? 0;
        pdfDocument.RenderingOptions.MarginBottom = pageLayout?.MarginBottom ?? 0;
        pdfDocument.RenderingOptions.MarginLeft = pageLayout?.MarginLeft ?? 0;
        pdfDocument.RenderingOptions.MarginRight = pageLayout?.MarginRight ?? 0;
        // Perform document generation
        pdfDocument.RenderHtmlAsPdf("<html><body><h1>Hello, IronPDF!</h1></body></html>").SaveAs("CustomLayoutDocument.pdf");
    }
}
[PageLayout(Size = IronPdf.Rendering.PdfPaperSize.A4, MarginTop = 20, MarginBottom = 20, MarginLeft = 10, MarginRight = 10)]
public class PdfGenerationWithLayoutAttributes
{
    public void GeneratePdf()
    {
        // Instantiate IronPDF PdfDocument
        var pdfDocument = new ChromePdfRenderer();
        // Retrieve PageLayoutAttribute using reflection
        var pageLayout = typeof(PdfGenerationWithLayoutAttributes)
            .GetCustomAttributes(typeof(PageLayoutAttribute), false)
            .FirstOrDefault() as PageLayoutAttribute;
        // Set layout values
        pdfDocument.RenderingOptions.PaperSize = pageLayout?.Size;
        pdfDocument.RenderingOptions.MarginTop = pageLayout?.MarginTop ?? 0;
        pdfDocument.RenderingOptions.MarginBottom = pageLayout?.MarginBottom ?? 0;
        pdfDocument.RenderingOptions.MarginLeft = pageLayout?.MarginLeft ?? 0;
        pdfDocument.RenderingOptions.MarginRight = pageLayout?.MarginRight ?? 0;
        // Perform document generation
        pdfDocument.RenderHtmlAsPdf("<html><body><h1>Hello, IronPDF!</h1></body></html>").SaveAs("CustomLayoutDocument.pdf");
    }
}
<PageLayout(Size := IronPdf.Rendering.PdfPaperSize.A4, MarginTop := 20, MarginBottom := 20, MarginLeft := 10, MarginRight := 10)>
Public Class PdfGenerationWithLayoutAttributes
	Public Sub GeneratePdf()
		' Instantiate IronPDF PdfDocument
		Dim pdfDocument = New ChromePdfRenderer()
		' Retrieve PageLayoutAttribute using reflection
		Dim pageLayout = TryCast(GetType(PdfGenerationWithLayoutAttributes).GetCustomAttributes(GetType(PageLayoutAttribute), False).FirstOrDefault(), PageLayoutAttribute)
		' Set layout values
		pdfDocument.RenderingOptions.PaperSize = pageLayout?.Size
		pdfDocument.RenderingOptions.MarginTop = If(pageLayout?.MarginTop, 0)
		pdfDocument.RenderingOptions.MarginBottom = If(pageLayout?.MarginBottom, 0)
		pdfDocument.RenderingOptions.MarginLeft = If(pageLayout?.MarginLeft, 0)
		pdfDocument.RenderingOptions.MarginRight = If(pageLayout?.MarginRight, 0)
		' Perform document generation
		pdfDocument.RenderHtmlAsPdf("<html><body><h1>Hello, IronPDF!</h1></body></html>").SaveAs("CustomLayoutDocument.pdf")
	End Sub
End Class
VB   C#

この例では、PageLayoutAttribute がページレイアウト設定をカプセル化するために使用され、属性値に基づいて動的な調整を可能にします。

結論

結論として、C#属性は、コード内にメタデータを埋め込むための非常に貴重なメカニズムであり、ツール、コンパイラ、および実行環境がそのコードを解釈および処理する方法に影響を与えます。 組み込み属性を利用する場合でもカスタム属性を作成する場合でも、開発者は属性を活用してコードの表現力を高め、ツールの統合を可能にし、アプリケーションの動作を形作ることができます。

C#属性とIronPDFの統合により、より繊細でダイナミックなPDF生成への道が開かれます。 メタデータのカスタマイズやレイアウト設定の微調整など、属性はIronPDFの機能を強化するための宣言的なアプローチを提供します。 可能性を探る際には、PDF生成タスクの具体的なニーズと、属性がIronPDFを使ったよりカスタマイズされた効率的なプロセスにどのように寄与するかを考慮してください。

IronPDFは、いくつかの制限がありますが、それらはライセンスで解除することができます。 ライセンス ライブラリの完全な機能をテストするために。

< 以前
C# String.Format(開発者向けの動作方法)
次へ >
C# デリゲート(開発者向けの仕組み)

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

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