Przejdź do treści stopki
POMOC .NET

Atrybuty C# (jak to działa dla programistów)

In the world of C# programming, metadata plays a crucial role in enriching code semantics and behavior. C# attributes emerge as powerful tools that empower developers to attach metadata to various entities in their code, shaping the way compilers, tools, and runtime environments interpret and interact with those entities.

In this comprehensive guide, we'll have a look at C# attributes, exploring their syntax, applications, and how they serve as a versatile mechanism for enhancing code expressiveness and functionality.

Atrybuty C#: wprowadzenie

Attributes, denoted by square brackets ([]), are declarative tags placed above code elements to provide additional information about them. This additional information, also known as metadata, doesn't affect the core functionality of the code but offers valuable insights to compilers, runtime environments, and tools.

In C#, an object attribute represents metadata associated with a program entity, like a class or method. Attribute instances, defined using attribute syntax, enhance the description of a program entity, such as using Conditional("DEBUG") to conditionally include code.

Here's a basic example of using an attribute in C#:

[Serializable]
public class Person
{
    // Class Implementation
}
[Serializable]
public class Person
{
    // Class Implementation
}
<Serializable>
Public Class Person
	' Class Implementation
End Class
$vbLabelText   $csharpLabel

In this example, the Serializable attribute indicates that instances of the Person class can be serialized.

Types of C# Attributes

Attributes are applied to various elements in C# code, including:

  1. Assembly: Applied to the entire assembly, influencing its behavior during compilation and execution.

    [assembly: AssemblyVersion("1.0.0.0")]
    [assembly: AssemblyVersion("1.0.0.0")]
    <Assembly: AssemblyVersion("1.0.0.0")>
    $vbLabelText   $csharpLabel
  2. Module: Applied to a module within an assembly, providing information about the module itself.

    [module: SomeCustomModuleAttribute]
    [module: SomeCustomModuleAttribute]
    <Module: SomeCustomModuleAttribute>
    $vbLabelText   $csharpLabel
  3. Type: Applied to types, influencing their behavior or providing additional information.

    [Serializable]
    public class Person
    {
        // Class Implementation
    }
    [Serializable]
    public class Person
    {
        // Class Implementation
    }
    <Serializable>
    Public Class Person
    	' Class Implementation
    End Class
    $vbLabelText   $csharpLabel
  4. Method: Applied to methods, altering their behavior or providing information to tools.

    [Obsolete("Use the newMethod instead.")]
    public void DeprecatedMethod()
    {
        // Method implementation
    }
    [Obsolete("Use the newMethod instead.")]
    public void DeprecatedMethod()
    {
        // Method implementation
    }
    <Obsolete("Use the newMethod instead.")>
    Public Sub DeprecatedMethod()
    	' Method implementation
    End Sub
    $vbLabelText   $csharpLabel
  5. Property, Field, Event, etc.: Applied to specific members within a type, offering metadata relevant to those members.

    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
    $vbLabelText   $csharpLabel

Tworzenie własnych atrybutów w C

While C# provides numerous built-in attributes, developers can create custom attributes to convey specific information about their code. Custom attributes are defined by creating a class that inherits from 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
}
<AttributeUsage(AttributeTargets.Class Or AttributeTargets.Method, AllowMultiple := True)>
Public Class CustomAttribute
	Inherits Attribute

	' Attribute Implementation
End Class
$vbLabelText   $csharpLabel

In this example, CustomAttribute can be applied to classes and methods, and the AllowMultiple property specifies whether multiple instances of the attribute are allowed on a single target. While creating a custom attributes class, an "Attribute" suffix is added to the class name to differentiate it from normal classes. The attribute constructor initializes these properties, and positional parameters play a role in passing values to these attributes, providing structured information in code.

Applications of C# Attributes

1. Code Documentation

Attributes play a crucial role in documenting code and providing additional information to developers or tools. For instance, the [Obsolete] attribute indicates that a particular element should no longer be used, and developers should migrate to an alternative.

[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
$vbLabelText   $csharpLabel

2. Serialization and Persistence

Attributes like [Serializable] inform the runtime environment that instances of a type can be serialized. This is crucial when dealing with scenarios like data persistence.

[Serializable]
public class Person
{
    // Class implementation
}
[Serializable]
public class Person
{
    // Class implementation
}
<Serializable>
Public Class Person
	' Class implementation
End Class
$vbLabelText   $csharpLabel

3. Code Analysis and Tools Integration

Attributes contribute to static analysis and code generation tools. For example, tools like unit testing frameworks use attributes like TestMethod to identify test methods.

[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
$vbLabelText   $csharpLabel

4. ASP.NET MVC Routing

In ASP.NET MVC, attributes are extensively used for routing. The Route attribute allows developers to specify the route template for an action method.

[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
$vbLabelText   $csharpLabel

Wprowadzenie do IronPDF: krótki przegląd

IronPDF Overview stands as a versatile library tailored for C# .NET Framework developers, offering an extensive set of tools for PDF generation and manipulation. From creating PDFs from HTML to extracting content from existing documents, IronPDF simplifies complex tasks, making it a valuable asset in the developer's toolkit.

C# Attributes (How It Works For Developer): Figure 1 - IronPDF webpage

Instalowanie IronPDF: szybki start

To begin leveraging the IronPDF library in your C# project, you can easily install the IronPDF NuGet package. Use the following command in your Package Manager Console:

Install-Package IronPdf

Alternatywnie można wyszukać "IronPDF" w menedżerze pakietów NuGet i zainstalować go stamtąd.

C# Attributes: A Quick Overview

C# attributes are declarative tags that provide additional information about entities in your code, such as classes, methods, or properties. They enable developers to attach metadata or define behavior without altering the core functionality of the code as mentioned above. As we move on exploring the integration of attributes with IronPDF, we'll discover how they can contribute to a more nuanced approach to PDF generation.

Ulepszanie generowania plików PDF za pomocą atrybutów C

1. Customizing Document Metadata

Attributes can be employed to enrich the metadata associated with the PDF document. IronPDF allows developers to customize metadata elements such as title, author, and subject. By using attributes, you can dynamically inject this information into the generated PDF. The following example demonstrates how to use different attribute classes with IronPDF:

// 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");
    }
}

// Usage
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");
    }
}

// Usage
PdfGenerationWithAttributes obj = new PdfGenerationWithAttributes();
obj.GeneratePdf();
' Define the DocumentMetadataAttribute
Public Class DocumentMetadataAttribute
	Inherits Attribute

	Public Property Title() As String
	Public Property Author() As String
	Public Property Subject() As String
End Class

<DocumentMetadata(Title := "Custom PDF Title", Author := "John Doe", Subject := "Document Subject")>
Public Class PdfGenerationWithAttributes
	Public Sub GeneratePdf()
		' Instantiate IronPDF PdfDocument
		Dim pdfDocument As New PdfDocument("StyledDocument.pdf")
		' Retrieve DocumentMetadataAttribute using reflection
		Dim documentMetadata = TryCast(GetType(PdfGenerationWithAttributes).GetCustomAttributes(GetType(DocumentMetadataAttribute), False).FirstOrDefault(), 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")
	End Sub
End Class

' Usage
Private obj As New PdfGenerationWithAttributes()
obj.GeneratePdf()
$vbLabelText   $csharpLabel

In this example, the DocumentMetadataAttribute serves as a custom attribute to convey metadata information, allowing for dynamic customization during PDF generation. The provided code defines a custom attribute class named DocumentMetadataAttribute in C#. Attributes are a way to add metadata or declarative information to program entities like classes, methods, or properties. These attributes are then used to edit the MetaData of a PDF document through reflection.

C# Attributes (How It Works For Developer): Figure 2 - Viewing outputted PDF's metadata through 'Document Properties'

2. Sterowanie układem pliku PDF za pomocą atrybutów

Atrybuty mogą być również wykorzystywane do kontrolowania układu dokumentu PDF. IronPDF oferuje opcje ustawiania rozmiaru strony, marginesów i orientacji. Korzystając z atrybutów, można sparametryzować te ustawienia układu w oparciu o konkretne wymagania:

// Define the PageLayoutAttribute
public class PageLayoutAttribute : Attribute
{
    public IronPdf.Rendering.PdfPaperSize Size { get; set; }
    public int MarginTop { get; set; }
    public int MarginBottom { get; set; }
    public int MarginLeft { get; set; }
    public int MarginRight { get; set; }
}

[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");
    }
}

// Usage
PdfGenerationWithLayoutAttributes obj = new PdfGenerationWithLayoutAttributes();
obj.GeneratePdf();
// Define the PageLayoutAttribute
public class PageLayoutAttribute : Attribute
{
    public IronPdf.Rendering.PdfPaperSize Size { get; set; }
    public int MarginTop { get; set; }
    public int MarginBottom { get; set; }
    public int MarginLeft { get; set; }
    public int MarginRight { get; set; }
}

[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");
    }
}

// Usage
PdfGenerationWithLayoutAttributes obj = new PdfGenerationWithLayoutAttributes();
obj.GeneratePdf();
' Define the PageLayoutAttribute
Public Class PageLayoutAttribute
	Inherits Attribute

	Public Property Size() As IronPdf.Rendering.PdfPaperSize
	Public Property MarginTop() As Integer
	Public Property MarginBottom() As Integer
	Public Property MarginLeft() As Integer
	Public Property MarginRight() As Integer
End Class

<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

' Usage
Private obj As New PdfGenerationWithLayoutAttributes()
obj.GeneratePdf()
$vbLabelText   $csharpLabel

In this example, the PageLayoutAttribute is used to encapsulate page layout settings, allowing for dynamic adjustments based on the attribute values.

Wnioski

Podsumowując, atrybuty C# stanowią nieoceniony mechanizm osadzania metadanych w kodzie, wpływając na sposób, w jaki narzędzia, kompilatory i środowiska uruchomieniowe interpretują i przetwarzają ten kod. Niezależnie od tego, czy korzystają z wbudowanych atrybutów, czy tworzą własne, programiści mogą wykorzystywać atrybuty do zwiększania wyrazistości kodu, umożliwiania integracji narzędzi oraz kształtowania zachowania swoich aplikacji.

Integracja atrybutów C# z IronPDF otwiera możliwości bardziej zróżnicowanego i dynamicznego generowania plików PDF. Niezależnie od tego, czy chodzi o dostosowywanie metadanych, czy o precyzyjne dostosowywanie ustawień układu, atrybuty zapewniają deklaratywne podejście do rozszerzania możliwości IronPDF. Rozważając dostępne możliwości, weź pod uwagę konkretne potrzeby związane z generowaniem plików PDF oraz to, w jaki sposób atrybuty mogą przyczynić się do bardziej dostosowanego i wydajnego procesu dzięki IronPDF.

IronPDF jest bezpłatny do celów programistycznych z kilkoma ograniczeniami, które można odblokować za pomocą licencji umożliwiającej pełne testowanie funkcjonalności IronPDF.

Często Zadawane Pytania

Czym są atrybuty C# i jak działają?

Atrybuty C# to tagi deklaratywne, których można używać do dołączania metadanych do elementów kodu, takich jak klasy, metody i właściwości. Zwiększają one wyrazistość i funkcjonalność kodu bez zmiany jego rdzenia, dostarczając dodatkowych informacji kompilatorom, środowiskom uruchomieniowym i narzędziom.

Jak utworzyć atrybut niestandardowy w języku C#?

Aby utworzyć atrybut niestandardowy w języku C#, należy zdefiniować klasę rozszerzającą klasę System.Attribute. Elementy docelowe można określić za pomocą atrybutu AttributeUsage, kontrolując, gdzie można zastosować atrybut niestandardowy.

W jaki sposób atrybuty usprawniają generowanie plików PDF?

Atrybuty mogą służyć do dostosowywania metadanych, takich jak tytuł i autor w dokumentach PDF, oraz do kontrolowania ustawień układu, takich jak rozmiar strony i marginesy. Biblioteki takie jak IronPDF wykorzystują atrybuty, aby umożliwić dynamiczne i dostosowane do potrzeb tworzenie plików PDF.

Do czego służy atrybut [Serializable] w języku C#?

Atrybut [Serializable] służy do wskazania, że instancje klasy mogą być serializowane. Jest to ważne dla trwałości danych i pracy ze strumieniami, umożliwiając konwersję obiektów do formatu, który można łatwo przechowywać lub przesyłać.

Jak można wykorzystać atrybuty w ASP.NET MVC?

W ASP.NET MVC atrybuty takie jak [Route] są wykorzystywane do definiowania szablonów routingu adresów URL dla akcji kontrolerów. Pomaga to tworzyć uporządkowane i czytelne struktury adresów URL, które zwiększają możliwości routingu aplikacji.

Jaką rolę odgrywają atrybuty w dokumentacji kodu?

Atrybuty takie jak [Obsolete] służą celom dokumentacyjnym, oznaczając elementy, których nie należy używać, sugerując alternatywy i ostrzegając programistów o przestarzałym kodzie.

W jaki sposób atrybuty pomagają w testowaniu jednostkowym?

Atrybuty w frameworkach do testowania jednostkowego, takie jak [TestMethod], umożliwiają identyfikację i wykonywanie metod testowych. Dostarczają one metadane, które narzędzia testujące wykorzystują do efektywnego organizowania i przeprowadzania testów.

Jakie znaczenie ma właściwość AllowMultiple atrybutów niestandardowych?

Właściwość AllowMultiple w atrybutach niestandardowych określa, czy do jednego elementu programu można zastosować wiele instancji atrybutu, zapewniając elastyczność w dołączaniu metadanych.

Czy atrybuty mogą być wykorzystywane do integracji narzędzi?

Tak, atrybuty ułatwiają integrację narzędzi, dostarczając metadane, które narzędzia mogą przetwarzać. Obejmuje to integrację z frameworkami do zadań takich jak serializacja, routing i generowanie dokumentów.

Jakie są typowe wbudowane atrybuty w języku C#?

Typowe wbudowane atrybuty w języku C# to [Serializable], [Obsolete], [Conditional] i [TestMethod]. Atrybuty te służą różnym celom, takim jak serializacja, deprecjacja, kompilacja warunkowa oraz identyfikacja metod testowych.

Jacob Mellor, Dyrektor Technologiczny @ Team Iron
Dyrektor ds. technologii

Jacob Mellor jest Chief Technology Officer w Iron Software i wizjonerskim inżynierem, pionierem technologii C# PDF. Jako pierwotny deweloper głównej bazy kodowej Iron Software, kształtuje architekturę produktów firmy od jej początku, przekształcając ją wspólnie z CEO Cameron Rimington w firmę liczą...

Czytaj więcej

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie