1024programmer Asp.Net C# Attribute knowledge points that every .NET developer should master

C# Attribute knowledge points that every .NET developer should master

C# Attribute knowledge points that every .NET developer should master

The previous article talked about the knowledge points of C# reflection. This article will introduce the knowledge points of C# attributes (Attribute). C# attributes (Attributes) are a powerful metadata mechanism used to add information to code elements (such as classes, methods, properties, etc.) to affect their behavior or provide additional information. This article will introduce the C# features that every .NET developer should be familiar with. I hope it will be helpful to everyone in development.

1. Basic concepts of characteristics

The common language runtime enables you to add keyword-like descriptive declarations (called attributes) to annotate programming elements (such as types, fields, methods, and properties), which are enclosed in square brackets ([]) Forms are attached to code elements and can contain parameters. Attributes are usually defined by creating a custom class that inherits from System.Attribute. The following is a simple feature definition example, which is the official example of .NET creating a minimal API by default:

 [HttpGet(Name = "GetWeatherForecast")]//Characteristics
   public IEnumerable Get()
   {
       return Enumerable.Range(1, 5).Select(index => new WeatherForecast
       {
           Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
           TemperatureC = Random.Shared.Next(-20, 55),
           Summary = Summaries[Random.Shared.Next(Summaries.Length)]
       })
       .ToArray();
   }
 

The above characteristics are the Get request characteristics of http, and the external link name is GetWeatherForecast.

Detailed explanation–>C#-Attribute

2. Examples of built-in features

C# provides some built-in features by default, such as [Obsolete], [Serializable] and [Conditional], etc. This makes it easy for .NET development to handle basic specific logical tasks.

[Obsolete] attribute: The [Obsolete] attribute is used to mark obsolete code. It can accept an optional message parameter that provides information about why the code is obsolete.

[Serializable] attribute: The [Serializable] attribute is used to mark a class as serializable so that objects can be converted into a byte stream. For example:

[Serializable]
 public class SerializableClass
 {
     //Members of the class
 }
 

3. Custom features

Of course, you can also customize features to meet the specific needs of the project. Usually custom features need to inherit the Attribute class, add the AttributeUsage feature to the class, and then handle the required logic below. For details, see my previous article on custom features. .NET Features (Attribute) Simple Customization. Below is a customized feature that displays author and other information.

[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
 public class AuthorInfoAttribute : Attribute
 {
     public string Author { get; }
     public string Version { get; }


     public AuthorInfoAttribute(string author, string version)
     {
         Author = author;
         Version = version;
     }
 }
 //Use properties
 [AuthorInfo("DotNet development job-hopping", "1.0")]
 public class MyAwesomeClass
 {
     //Members of the class
 }
 

4. Feature application scenarios

So where are features usually used?

Features have a variety of application scenarios in the .NET ecosystem, such as the generation of code documents; code analysis and verification, such as attribute Name field length verification, etc.; can dependency injection; and most importantly, can implement AOP (for Aspect programming), such as logging and performance monitoring.

5. Runtime and compile-time usage of features

Attributes in C# have both runtime uses, through the reflection mechanism, code elements to which attributes have been applied can be dynamically inspected and manipulated while the program is running, and compile-time uses, which can affect the behavior of the compiler at compile time, such as conditionals Compilation, code generation, and static analysis, providing developers with the flexibility and ability to metadata tag and customize code at different stages of the code (compile and runtime).

6. Attribute access of characteristics

Through reflection, you can access attributes and their parameters that have been applied to code elements. The previous article introducing reflection (C# reflection knowledge points) has already been introduced. The following demonstrates how to check and obtain custom attribute information on a class.

Type type = typeof(MyAwesomeClass);
 var attributes = type.GetCustomAttributes(typeof(AuthorInfoAttribute), false);
 if (attributes.Length > 0 && attributes[0] is AuthorInfoAttribute authorInfo)
 {
     Console.WriteLine($"Author: {authorInfo.Author}, Version number: {authorInfo.Version}");
 }
 //The above code will print the characteristics of the MyAwesomeClass class, showing the author and version number of the characteristic attributes.
 

Conclusion

This article describes some knowledge points about C# features, such as custom features, built-in features, obtaining feature content, etc. These knowledge points should be mastered in .NET development.

I hope the C# feature knowledge provided in this article will be helpful to every .NET developer. What else do you know about C# features? joyousWelcome to leave a message to discuss or complain about this article.

Reference:

1. Microsoft official website:

learn.microsoft.com/zh-cn/dotnet/csharp/language-reference/language-specification/attributes

2. AI query

**Recommended reading

1. .NET’s ubiquitous attributes (Attribute) 1-Exploration

2. .NET’s ubiquitous attributes (Attribute) 2-simple customization

3. Interview essentials: Let’s talk about C# attributes (Attribute)

Source public account: DotNet development job hopping
 
This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/c-attribute-knowledge-points-that-every-net-developer-should-master/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索