跳過到頁腳內容
.NET幫助

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

在 C# 程式設計的世界裡,元資料在豐富程式碼語義和行為方面扮演著重要的角色。 C#屬性作為強大的工具出現,賦予開發人員在程式碼中為各種實體附加元資料的能力,塑造編譯器、工具和執行時環境詮釋這些實體並與之互動的方式。

在本綜合指南中,我們將介紹 C# 屬性,探討其語法、應用,以及它們如何成為增強程式碼表達力和功能的多功能機制。

瞭解 C# 屬性:入門

以方括號 ([]) 表示的屬性 (Attributes) 是放置在程式碼元素上方的宣告性標籤,用以提供這些元素的附加資訊。 這些附加資訊(也稱為元資料)不會影響程式碼的核心功能,但對編譯器、執行時環境和工具提供了寶貴的見解。

在 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.程式集:應用於整個程式集,在編譯和執行過程中影響其行為。

```csharp
[assembly: AssemblyVersion("1.0.0.0")]
```

2.模組:套用於程序集內的模組,提供模組本身的相關資訊。

```csharp
[module: SomeCustomModuleAttribute]
```

3.類型: 應用於類型,影響其行為或提供額外資訊。

```csharp
[Serializable]
public class Person
{
    // Class Implementation
}
```

4.方法: 應用於方法,改變其行為或提供資訊給工具。

```csharp
[Obsolete("Use the newMethod instead.")]
public void DeprecatedMethod()
{
    // Method implementation
}
```

5.屬性、欄位、事件等:套用於類型中的特定成員,提供與這些成員相關的元資料。

```csharp
public class Example
{
    [DefaultValue(42)]
    public int Answer { get; set; }
}
```

在 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# Attributes (How It Works For Developer):圖 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 。 屬性(Attributes)是為類別、方法或屬性等程式實體新增元資料或宣告性資訊的一種方式。 然後透過反射,使用這些屬性來編輯 PDF 文件的 MetaData

C# Attributes (How It Works For Developer):圖 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 創作。

C# 中的 [Serializable] 屬性用來做什麼?

Serializable] 屬性用來表示類別的實體可以序列化。這對於資料持久化和流的處理非常重要,可讓物件轉換成容易儲存或傳輸的格式。

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

在 ASP.NET MVC 中,[Route]等屬性可用於定義控制器動作的 URL 路由範本。這有助於建立有組織且可讀的 URL 結構,強化應用程式的路由功能。

屬性在程式碼文件中扮演什麼角色?

類似 [Obsolete] 之類的屬性可透過標示不應使用的元素、建議替代方案,以及向開發人員提供有關廢棄程式碼的警告,來達到文件的目的。

屬性如何協助單元測試?

單元測試架構中的屬性,例如 [TestMethod],能夠識別和執行測試方法。它們提供了元資料,測試工具可利用這些元資料來有效地組織和執行測試。

自訂屬性的 AllowMultiple 屬性有什麼意義?

自訂屬性中的 AllowMultiple 屬性可決定是否可將屬性的多個實例套用至單一程式元素,提供附加元資料方式的彈性。

屬性可以用於工具整合嗎?

是的,屬性透過提供工具可以處理的元資料來促進工具整合。這包括與序列化、路由和文件產生等任務的框架整合。

C# 中有哪些常見的內建屬性?

C# 中常見的內建屬性包括 [Serializable]、[Obsolete]、[Conditional] 和 [TestMethod]。這些屬性有各種用途,例如序列化、廢棄、有條件的編譯,以及識別測試方法。

Jacob Mellor, Team Iron 首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。