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

```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 创建。

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

[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將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

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

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我