.NET 幫助

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

發佈 2024年2月18日
分享:

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

在本綜合指南中,我們將了解C#屬性,探索其語法、應用以及它們如何作為一種靈活的機制來增強代碼的表達性和功能性。

理解 C#屬性:初學指南

屬性使用方括號表示 ([]),在程式碼元素上方放置的聲明標籤,以提供有關它們的其他信息。這些額外信息也稱為元數據,不會影響程式碼的核心功能,但為編譯器、運行環境和工具提供了寶貴的見解。

在 C# 中,物件屬性代表與程序實體(如類別或方法)相關聯的元數據。使用屬性語法定義的屬性實例可增強程序實體(例如使用 Conditional)的描述。(「調試」)在C#中使用屬性有條件地包含程式碼。

以下是一個使用屬性的基本範例:

[Serializable]
public class Person
{
    // Class Implementation
}
[Serializable]
public class Person
{
    // Class Implementation
}
<Serializable>
Public Class Person
	' Class Implementation
End Class
VB   C#

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

種類的 C# 屬性

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

  1. Assembly: 應用於整個程序集,影響其在編譯和執行期間的行為。
    [assembly: AssemblyVersion("1.0.0.0")]
    [assembly: AssemblyVersion("1.0.0.0")]
<Assembly: AssemblyVersion("1.0.0.0")>
VB   C#
  1. 模組: 應用於組件內的一個模組,提供有關該模組本身的信息。
    [module: SomeCustomModuleAttribute]
    [module: SomeCustomModuleAttribute]
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#
  1. 類型: 應用於類型,影響其行為或提供額外信息。
    [Serializable]
        public class Person
        {
            // Class Implementation
        }
    [Serializable]
        public class Person
        {
            // Class Implementation
        }
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#
  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
VB   C#
  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
VB   C#

在 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
VB   C#

在這個範例中,CustomAttribute 可以應用於類別和方法,而且 AllowMultiple 屬性指定是否允許在單一目標上使用多個屬性的實例。在創建自定義屬性類別時,會在類別名稱後加上屬性後綴,以區別於一般類別。屬性建構函式會初始化這些屬性,且位置參數在傳遞值給這些屬性時扮演角色,為程式碼提供結構化的資訊。

C# 屬性應用

1. 程式碼文件

屬性在記錄程式碼和提供額外資訊給開發人員或工具方面扮演著至關重要的角色。例如,[過時] 屬性表示某個特定元素不應再使用,開發人員應遷移到替代方案。

[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
VB   C#

2. 序列化和持久化

屬性如 [可序列化] 告知運行時環境某類型的實例可以被序列化。這在處理數據持久化等情況時至關重要。

[Serializable]
public class Person
{
    // Class implementation
}
[Serializable]
public class Person
{
    // Class implementation
}
<Serializable>
Public Class Person
	' Class implementation
End Class
VB   C#

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
VB   C#

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
VB   C#

介紹 IronPDF: 簡介

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");
'	}
'}
VB   C#

在此範例中,DocumentMetadataAttribute 作為一個自定義屬性來傳遞元數據資訊,允許在 PDF 生成期間進行動態自定義。提供的程式碼定義了一個名為 DocumentMetadataAttribute 的自定義屬性類別,使用 C# 編寫。屬性是一種向程式實體(例如類別、方法或屬性)添加元數據或聲明性資訊的方法。這些屬性接著通過反射來編輯 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
VB   C#

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

結論

總之,C# 屬性作為將元資料嵌入代碼中的一種寶貴機制,影響了工具、編譯器和運行時環境如何解釋和處理該代碼。無論是使用內建屬性還是自定義屬性,開發者都可以利用屬性來增強代碼的表現力,實現工具集成,並塑造其應用程序的行為。

C# 屬性與 IronPDF 的集成為生成更細膩和動態的 PDF 提供了可能。不論是自定義元資料還是微調佈局設置,屬性都提供了一種聲明式方法來增強 IronPDF 的功能。在探索這些可能性時,請考慮您的 PDF 生成任務的具體需求,以及屬性如何有助於通過 IronPDF 實現更加定制和高效的過程。

IronPDF 在一定限制下可免費開發,通過購買許可證可以解鎖這些限制。 許可證 測試該程式庫的完整功能。

< 上一頁
C# 字串格式化(開發者使用說明)
下一個 >
C# 委派(開發者如何使用)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >