跳過到頁腳內容
.NET幫助

C# 屬性(對於開發者的運行原理)

在 C# 程式設計的世界中,元資料在豐富代碼語義和行為方面發揮著至關重要的作用。 C# 屬性作為強大的工具出現,使開發人員能夠將元資料附加到代碼中的各種實體,塑造編譯器、工具和運行時環境解釋和交互這些實體的方式。

在這份全面的指南中,我們將查看 C# 屬性,探討其語法、應用以及它們如何作為增強代碼表達力和功能的多功能機制。

理解 C# 屬性:入門

屬性用方括號 ([]) 表示,是位於代碼元素上方的聲明性標籤,用於提供該元素的附加信息。 這些附加信息,也稱為元資料,不會影響代碼的核心功能,但可為編譯器、運行時環境和工具提供有價值的信息。

在 C# 中,對象屬性表示與程序實體(如類或方法)相關聯的元資料。 定義為屬性語法的屬性實例可增強程序實體的描述,例如使用 Conditional("DEBUG") 有條件地包含代碼。

以下是 C# 中使用屬性的一個基本示例:

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

在此示例中,Serializable 屬性指示 Person 類的實例可以序列化。

C# 屬性的類型

屬性應用於 C# 代碼中的各種元素,包括:

  1. 程序集:應用於整個程序集,在編譯和執行過程中影響其行為。

    [assembly: AssemblyVersion("1.0.0.0")]
    [assembly: AssemblyVersion("1.0.0.0")]
    <Assembly: AssemblyVersion("1.0.0.0")>
    $vbLabelText   $csharpLabel
  2. 模塊:應用於程序集中的模塊,提供有關模塊本身的信息。

    [module: SomeCustomModuleAttribute]
    [module: SomeCustomModuleAttribute]
    IRON VB CONVERTER ERROR developers@ironsoftware.com
    $vbLabelText   $csharpLabel
  3. 類型:應用於類型,影響其行為或提供附加信息。

    [Serializable]
    public class Person
    {
        // Class Implementation
    }
    [Serializable]
    public class Person
    {
        // Class Implementation
    }
    <Serializable>
    Public Class Person
    	' Class Implementation
    End Class
    $vbLabelText   $csharpLabel
  4. 方法:應用於方法,改變其行為或向工具提供信息。

    [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. 屬性、字段、事件等:應用於類型中的特定成員,提供與這些成員相關的元資料。

    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

在 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
}
<AttributeUsage(AttributeTargets.Class Or AttributeTargets.Method, AllowMultiple := True)>
Public Class CustomAttribute
	Inherits Attribute

	' Attribute Implementation
End Class
$vbLabelText   $csharpLabel

在此示例中,CustomAttribute 可應用於類和方法,並且 AllowMultiple 屬性指定單個目標上是否允許多個屬性實例。 在創建自定義屬性類時,會在類名後加上"Attribute"後綴,以區分它們與普通類。 屬性構造函數初始化這些屬性,位置參數在將值傳遞給這些屬性時發揮作用,從而在代碼中提供結構化信息。

C# 屬性的應用

1. 代碼文檔

屬性在文檔代碼和向開發人員或工具提供附加信息方面具有重要作用。 例如,[Obsolete] 屬性指示不應再使用特定元素,開發人員應遷移到另一種替代方案。

[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. 序列化和持久化

[Serializable] 等屬性通知運行時環境類型的實例可以序列化。 這在處理數據持久性等場景時至關重要。

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

3. 代碼分析和工具集成

屬性有助於靜態分析和代碼生成工具。 例如,單元測試框架之類的工具使用 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
$vbLabelText   $csharpLabel

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

介紹 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 生成

1. 自定義文檔元資料

可以使用屬性來豐富與 PDF 文檔關聯的元資料。 IronPDF 允許開發人員自定義元數據元素,例如標題、作者和主題。 通過使用屬性,可以在生成的 PDF 中動態插入此信息。 以下示例說明了如何在 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

在此示例中,DocumentMetadataAttribute 作為自定義屬性來傳達元數據信息,允許 PDF 生成期間的動態自定義。 提供的代碼在 C# 中定義了一個名為 DocumentMetadataAttribute 的自定義屬性類。 屬性是一種向程序實體(例如類、方法或屬性)添加元數據或聲明性信息的方法。 然後這些屬性通過反射用於編輯 PDF 文檔的 MetaData

C# 屬性(它是如何為開發人員工作的):圖 2 - 通過“文檔屬性”查看輸出 PDF 的元數據

2. 使用屬性控制 PDF 布局

屬性也可以用來控制 PDF 文檔的布局。 IronPDF 提供設置頁面大小、邊距和方向的選項。 通過使用屬性,您可以根據特定要求對這些布局設置進行參數化:

// 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

在此示例中,PageLayoutAttribute 用於封裝頁面布局設置,允許根據屬性值進行動態調整。

結論

總之,C# 屬性作為嵌入元數據於代碼中的一個無價機制,影響工具、編譯器和運行時環境對代碼的解釋和處理方式。 無論是利用內置屬性還是打造自定義屬性,開發人員都可以利用屬性增強代碼表達力、實現工具集成並塑造應用程序的行為。

C# 屬性與 IronPDF 的集成打開了更細微和動態的 PDF 生成途徑。 無論是自定義元數據還是微調布局設置,屬性提供了一種聲明性的方法來增強 IronPDF 的功能。 當您探索可能性時,請考慮 PDF 生成任務的特定需求,以及屬性如何促進更量身定制和更高效的流程與 IronPDF。

IronPDF 免費用於開發,但有一些限制,您可以通過許可來解鎖完整的 IronPDF 功能測試

常見問題解答

什么是 C# 特性及其功能如何?

C# 特性是声明性标签,可用于附加元数据到代码实体,如类、方法和属性。它们在不改变核心代码的情况下增强代码表达性和功能,为编译器、运行时环境和工具提供额外的信息。

如何在 C# 中创建自定义特性?

要在 C# 中创建自定义特性,您需要定义一个继承自 System.Attribute 的类。您可以使用 AttributeUsage 特性来指定目标元素,控制自定义特性可以应用的位置。

特性如何增强 PDF 生成?

特性可用于自定义 PDF 文档中的元数据,如标题和作者,以及控制页面大小和边距等布局设置。IronPDF 等库利用特性能实现动态和定制的 PDF 创建。

[Serializable] 特性在 C# 中用于什么?

[Serializable] 特性用于指示类的实例可以被序列化。这对于数据持久性和流操作很重要,允许对象转换为易于存储或传输的格式。

特性在 ASP.NET MVC 中如何使用?

在 ASP.NET MVC 中,诸如 [Route] 的特性用于定义控制器操作的 URL 路由模板。这有助于创建有组织且可读的 URL 结构,提升应用程序的路由能力。

特性在代码文档中扮演什么角色?

诸如 [Obsolete] 的特性起到文档作用,通过标记不应使用的元素,提出替代方案,并向开发人员提供关于已弃用代码的警告。

特性如何帮助单元测试?

单元测试框架中,诸如 [TestMethod] 的特性用于识别和执行测试方法。它们提供的元数据被测试工具用来有效地组织和运行测试。

自定义特性的 AllowMultiple 属性有什么重要性?

自定义特性的 AllowMultiple 属性决定了是否可以对单个程序元素应用多个特性实例,提供元数据附加的灵活性。

特性可以用于工具集成吗?

是的,特性通过提供工具可处理的元数据来促进工具集成。这包括与用于序列化、路由和文档生成等任务的框架集成。

C# 中有哪些常见的内置特性?

C# 的常见内置特性包括 [Serializable]、[Obsolete]、[Conditional] 和 [TestMethod]。这些特性用于序列化、弃用、条件编译和识别测试方法等各种目的。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。