.NET 幫助

C# 屬性(開發人員如何運作)

Chipego
奇佩戈·卡林达
2024年2月18日
分享:

在 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
  1. 模組:適用於組件中的模組,提供有關該模組本身的資訊。
    [module: SomeCustomModuleAttribute]
    [module: SomeCustomModuleAttribute]
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel
  1. 類型:應用於類型,影響其行為或提供附加資訊。
    [Serializable]
        public class Person
        {
            // Class Implementation
        }
    [Serializable]
        public class Person
        {
            // Class Implementation
        }
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel
  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
$vbLabelText   $csharpLabel
  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
$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
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

在此範例中,CustomAttribute 可應用於類別和方法,而 AllowMultiple 屬性指定是否允許在單一目標上存在多個屬性的實例。 在創建自定義屬性類時,會在類名後添加屬性後綴,以將其與普通類區分開來。 屬性構造函數初始化這些屬性,位置參數在向這些屬性傳遞值時顯示作用,為代碼提供結構化信息。

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

序列化和持久性

[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 中使用不同的屬性類別:

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");
'	}
'}
$vbLabelText   $csharpLabel

在此範例中,DocumentMetadataAttribute 作為自定義屬性來傳遞元數據資訊,允許在 PDF 生成期間進行動態自定義。 所提供的代碼在 C# 中定義了一個名為DocumentMetadataAttribute的自定義屬性類。 屬性是一種為類別、方法或屬性等程式實體添加元數據或宣告性資訊的方式。 這些屬性然後用於通過反射編輯 PDF 文件的MetaData

C# 屬性(對開發者的運作方式):圖2 - 通過「文件屬性」查看輸出PDF的元數據

2. 使用屬性控制 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
$vbLabelText   $csharpLabel

在此範例中,PageLayoutAttribute 用於封裝頁面佈局設定,允許根據屬性值動態調整。

結論

總之,C# 屬性是將中繼資料嵌入代碼中的一種寶貴機制,它影響工具、編譯器和運行時環境如何解釋和處理該代碼。 無論是使用內建屬性還是自製客製化屬性,開發人員都可以利用屬性來增強程式碼的表達能力、啟用工具整合並塑造應用程式的行為。

將 C# 屬性與 IronPDF 整合可開啟更精細且動態的 PDF 生成方法。 無論是自訂中繼資料或微調版面設定,屬性提供了一種宣告性的方法來增強IronPDF的功能。 在您探索可能性時,請考慮您的 PDF 生成任務的具體需求,以及屬性如何能夠通過 IronPDF 貢獻於更加量身定制和高效的過程。

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

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
C# 字串格式化(開發者使用說明)
下一個 >
C# 委派(開發者如何使用)