要?jiǎng)?chuàng)建自己的C#自定義屬性,首先需定義一個(gè)繼承自System.Attribute的類,接著添加構(gòu)造函數(shù)和屬性,並通過(guò)AttributeUsage指定適用範(fàn)圍,最後通過(guò)反射讀取並使用它們。例如,定義[CustomAuthor("John")]屬性以標(biāo)記代碼作者,應(yīng)用時(shí)使用[CustomAuthor("Alice")]修飾類或方法,隨後通過(guò)Attribute.GetCustomAttribute方法在運(yùn)行時(shí)獲取屬性信息。常見(jiàn)用途包括驗(yàn)證、序列化控制、依賴注入和單元測(cè)試等,建議將屬性邏輯保持輕量,並合理限制其使用範(fàn)圍。
C# attributes let you add metadata or declarative information to your code elements like classes, methods, properties, etc. They're commonly used for things like serialization, validation, logging, and more. You've probably seen them before, like [Serializable]
or [Obsolete]
. But what if you want to create your own?

Here's how to understand and build your own custom attribute in C#.
What Exactly Is a Custom Attribute?
An attribute is essentially a class that inherits from System.Attribute
. When you create your own, you're defining a type that can be attached to various parts of your code to provide additional information at runtime (or compile time).

For example, you might create a [CustomAuthor("John")]
attribute to mark who wrote a specific class.
Custom attributes are useful when you want to inspect code structure or behavior through reflection, or when you're building frameworks or libraries that need to respond to metadata.

How to Create a Custom Attribute
Creating a custom attribute is straightforward. Here's how:
- Define a class that inherits from
Attribute
- Add constructors and properties as needed
- Apply the attribute to code elements
Here's a simple example:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class CustomAuthorAttribute : Attribute { public string AuthorName { get; } public CustomAuthorAttribute(string authorName) { AuthorName = authorName; } }
Now you can use it like this:
[CustomAuthor("Alice")] public class MyService { [CustomAuthor("Bob")] public void DoWork() { // Method logic } }
A few notes:
- You can control where the attribute can be applied using
[AttributeUsage]
. - You can include multiple parameters or properties.
- The constructor defines what you can set when applying the attribute.
How to Use Custom Attributes in Code
Once you've defined and applied your custom attribute, you'll probably want to access it at runtime. That's where reflection comes in.
Here's how you can check for your [CustomAuthor]
attribute on a class or method:
var type = typeof(MyService); var classAttribute = (CustomAuthorAttribute)Attribute.GetCustomAttribute( type, typeof(CustomAuthorAttribute)); Console.WriteLine($"Class author: {classAttribute?.AuthorName}"); var method = type.GetMethod("DoWork"); var methodAttribute = (CustomAuthorAttribute)Attribute.GetCustomAttribute( method, typeof(CustomAuthorAttribute)); Console.WriteLine($"Method author: {methodAttribute?.AuthorName}");
This is useful in scenarios like:
- Logging or auditing code authors
- Building a plugin system that scans for specific attributes
- Custom validation or behavior based on metadata
Just remember: reflection can be slow, so avoid doing it in performance-critical paths unless you cache the results.
Common Use Cases and Tips
- Validation attributes – Like
[Required]
or[Range]
in ASP.NET - Serialization control – For example,
[JsonProperty("name")]
in JSON libraries - Dependency injection markers – Some frameworks use attributes to auto-register services
- Testing frameworks – Attributes like
[Test]
or[SetUp]
are common in unit testing tools
Tips:
- Keep your attribute logic lightweight – they're metadata, not business logic
- Use
AttributeUsage
carefully – restrict to only what makes sense - You can combine attributes with reflection-based services to build extensible systems
So that's the core of custom attributes in C#. You define a class, apply it to code elements, and then use reflection to read and act on it later. It's not complicated once you get the hang of it, but it opens up a lot of possibilities for clean, extensible code design.
基本上就這些.
以上是什麼是C#屬性以及如何創(chuàng)建自定義屬性?的詳細(xì)內(nèi)容。更多資訊請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費(fèi)脫衣圖片

Undresser.AI Undress
人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強(qiáng)大的PHP整合開(kāi)發(fā)環(huán)境

Dreamweaver CS6
視覺(jué)化網(wǎng)頁(yè)開(kāi)發(fā)工具

SublimeText3 Mac版
神級(jí)程式碼編輯軟體(SublimeText3)

自定義特性(CustomAttributes)是C#中用於向代碼元素附加元數(shù)據(jù)的機(jī)制,其核心作用是通過(guò)繼承System.Attribute類來(lái)定義,並在運(yùn)行時(shí)通過(guò)反射讀取,實(shí)現(xiàn)如日誌記錄、權(quán)限控制等功能。具體包括:1.CustomAttributes是聲明性信息,以特性類形式存在,常用於標(biāo)記類、方法等;2.創(chuàng)建時(shí)需定義繼承自Attribute的類,並用AttributeUsage指定應(yīng)用目標(biāo);3.應(yīng)用後可通過(guò)反射獲取特性信息,例如使用Attribute.GetCustomAttribute();

在C#中設(shè)計(jì)不可變對(duì)象和數(shù)據(jù)結(jié)構(gòu)的核心是確保對(duì)象創(chuàng)建後狀態(tài)不可修改,從而提升線程安全性和減少狀態(tài)變化導(dǎo)致的bug。 1.使用readonly字段並配合構(gòu)造函數(shù)初始化,確保字段僅在構(gòu)造時(shí)賦值,如Person類所示;2.對(duì)集合類型進(jìn)行封裝,使用ReadOnlyCollection或ImmutableList等不可變集合接口,防止外部修改內(nèi)部集合;3.使用record簡(jiǎn)化不可變模型定義,默認(rèn)生成只讀屬性和構(gòu)造函數(shù),適合數(shù)據(jù)建模;4.創(chuàng)建不可變集合操作時(shí)推薦使用System.Collections.Imm

處理大量數(shù)據(jù)時(shí),C#可通過(guò)流式處理、並行異步和合適的數(shù)據(jù)結(jié)構(gòu)實(shí)現(xiàn)高效。 1.使用流式處理逐條或分批讀取,如StreamReader或EFCore的AsAsyncEnumerable,避免內(nèi)存溢出;2.合理使用並行(Parallel.ForEach/PLINQ)與異步(async/await Task.Run),控制並發(fā)數(shù)量並註意線程安全;3.選擇高效數(shù)據(jù)結(jié)構(gòu)(如Dictionary、HashSet)和序列化庫(kù)(如System.Text.Json、MessagePack),減少查找時(shí)間和序列化開(kāi)銷。

反射是C#中用於運(yùn)行時(shí)動(dòng)態(tài)分析和修改程序結(jié)構(gòu)的功能,核心作用包括獲取類型信息、動(dòng)態(tài)創(chuàng)建對(duì)象、調(diào)用方法及檢查程序集。常見(jiàn)應(yīng)用場(chǎng)景有:1.自動(dòng)綁定數(shù)據(jù)模型,如將字典數(shù)據(jù)映射到類實(shí)例;2.實(shí)現(xiàn)插件系統(tǒng),通過(guò)加載外部DLL並調(diào)用其接口;3.支持自動(dòng)化測(cè)試與日誌記錄,如執(zhí)行特定特性方法或自動(dòng)記錄日誌。使用時(shí)需注意性能開(kāi)銷、封裝性破壞和調(diào)試?yán)щy等問(wèn)題,優(yōu)化方式包括緩存類型信息、使用委託提高調(diào)用效率及生成IL代碼等。合理利用反射可提升系統(tǒng)的靈活性與通用性。

寫好C#代碼的關(guān)鍵在于可維護(hù)性和可測(cè)試性。合理劃分職責(zé),遵循單一職責(zé)原則(SRP),將數(shù)據(jù)訪問(wèn)、業(yè)務(wù)邏輯和請(qǐng)求處理分別由Repository、Service和Controller承擔(dān),提升結(jié)構(gòu)清晰度和測(cè)試效率。多用接口和依賴注入(DI),便于替換實(shí)現(xiàn)、擴(kuò)展功能和進(jìn)行模擬測(cè)試。單元測(cè)試應(yīng)隔離外部依賴,使用Mock工具驗(yàn)證邏輯,確??焖俜€(wěn)定執(zhí)行。規(guī)范命名和拆分小函數(shù),提高可讀性和維護(hù)效率。堅(jiān)持結(jié)構(gòu)清晰、職責(zé)分明、測(cè)試友好的原則,能顯著提升開(kāi)發(fā)效率和代碼質(zhì)量。

在ASP.NETCore中創(chuàng)建自定義中間件,可通過(guò)編寫類並註冊(cè)實(shí)現(xiàn)。 1.創(chuàng)建包含InvokeAsync方法的類,處理HttpContext和RequestDelegatenext;2.在Program.cs中使用UseMiddleware註冊(cè)。中間件適用於日誌記錄、性能監(jiān)控、異常處理等通用操作,與MVC過(guò)濾器不同,其作用於整個(gè)應(yīng)用,不依賴控制器。合理使用中間件可提升結(jié)構(gòu)靈活性,但應(yīng)避免影響性能。

使用LINQ時(shí)應(yīng)遵循以下要點(diǎn):1.在聲明式數(shù)據(jù)操作如過(guò)濾、轉(zhuǎn)換或聚合數(shù)據(jù)時(shí)優(yōu)先使用LINQ,避免在有副作用或性能關(guān)鍵的場(chǎng)景強(qiáng)制使用;2.理解延遲執(zhí)行特性,源集合修改可能導(dǎo)致意外結(jié)果,需根據(jù)需求選擇延遲或立即執(zhí)行;3.注意性能與內(nèi)存開(kāi)銷,鍊式調(diào)用可能產(chǎn)生中間對(duì)象,性能敏感代碼可改用循環(huán)或Span;4.保持查詢簡(jiǎn)潔易讀,複雜邏輯拆分為多個(gè)步驟,避免過(guò)度嵌套和混合多種操作。

泛型約束用於限制類型參數(shù)以確保特定行為或繼承關(guān)係,協(xié)變則允許子類型轉(zhuǎn)換。例如,whereT:IComparable確保T可比較;協(xié)變?nèi)鏘Enumerable允許IEnumerable轉(zhuǎn)為IEnumerable,但僅限讀取,不可修改。常見(jiàn)約束包括class、struct、new()、基類和接口,多約束用逗號(hào)分隔;協(xié)變需用out關(guān)鍵字且只適用於接口和委託,與逆變(in關(guān)鍵字)不同。注意協(xié)變不支持類,不能隨意轉(zhuǎn)換,且約束影響靈活性。
