English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Attribute(Attribute)are declarative tags used to pass behavior information of various elements in the program (such as classes, methods, structures, enumerations, components, etc.) at runtime. You can add declarative information to the program by using attributes. A declarative tag is described by placing square brackets ([ ]) before the element to which it is applied.
The attribute(Attribute) is used to add metadata, such as compiler instructions and comments, descriptions, methods, classes, and other information. .Net Framework provides two types of attributes:predefinedattributes andCustomAttribute.
The syntax for specifying the attribute(Attribute) is as follows:
[attribute(positional_parameters, name_parameter = value, ...)] element
The name and value of the attribute(Attribute) are specified within square brackets, placed before the element to which it is applied. positional_parameters specifies the required information, name_parameter specifies optional information.
.Net Framework provides three predefined attributes:
AttributeUsage
Conditional
Obsolete
Predefined attributes AttributeUsage Describes how to use a custom attribute class. It specifies the types of items to which the attribute can be applied.
The syntax for specifying this attribute is as follows:
[AttributeUsage( validon, AllowMultiple=allowmultiple, Inherited=inherited )]
Among them:
The parameter validon specifies the language elements to which the attribute can be applied. It is an enumerator AttributeTargets the combination of values. The default value is AttributeTargets.All。
parameter (Optional) The inherited property (property) provides a boolean value. If true, the attribute is multi-use. The default value is false (single-use). . allowmultiple
parameter AllowMultiple(Optional) The inherited property (property) provides a boolean value. If true, the attribute is multi-use. The default value is false (single-use). Inherited The property (property) provides a boolean value. If true, this attribute can be inherited by derived classes. The default value is false (not inherited).
For example:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)
This predefined attribute marks a conditional method whose execution depends on the specified preprocessing identifier.
It will cause conditional compilation of method calls, depending on the specified value, such as Debug or Trace. For example, when debugging code, it displays the value of variables.
The syntax for specifying this attribute is as follows:
[Conditional( conditionalSymbol )]
For example:
[Conditional("DEBUG")]
The following example demonstrates the feature:
#define DEBUG using System; using System.Diagnostics; public class Myclass { [Conditional("DEBUG")] public static void Message(string msg) { Console.WriteLine(msg); } } class Test { static void function1() { Myclass.Message("In Function 1. function2(); } static void function2() { Myclass.Message("In Function 2. } public static void Main() { Myclass.Message("In Main function."); function1(); Console.ReadKey(); } }
When the above code is compiled and executed, it will produce the following result:
In Main function In Function 1 In Function 2
This predefined attribute marks program elements that should not be used. It allows you to notify the compiler to discard a specific target element. For example, when a new method is used in a class, but you still want to keep the old method in the class, you can mark it as obsolete (outdated) by displaying a message indicating that the new method should be used instead of the old method.
The syntax for specifying this attribute is as follows:
[Obsolete( message )] [Obsolete( message, iserror )]
Among them:
parameter messageIt is a string that describes why the item is obsolete and what should be used instead.
parameter iserrorIt is a boolean value. If this value is true, the compiler should treat the use of the item as an error. The default value is false (the compiler generates a warning).
The following example demonstrates the feature:
using System; public class MyClass { [Obsolete("Don't use OldMethod, use NewMethod instead", true)] static void OldMethod() { Console.WriteLine("It is the old method"); } static void NewMethod() { Console.WriteLine("It is the new method"); } public static void Main() { OldMethod(); } }
When you try to compile the program, the compiler will output an error message indicating:
Don't use OldMethod, use NewMethod instead
.Net framework allows the creation of custom features to store declarative information, which can be retrieved at runtime. This information can be associated with any target element according to design standards and application needs.
Creating and using custom features involves four steps:
Declare a custom feature
Build a custom feature
Apply custom features to target program elements
Access features through reflection
The last step involves writing a simple program to read metadata to find various symbols. Metadata is data and information used to describe other data. The program should use reflection to access features at runtime. We will discuss this in detail in the next chapter.
A new custom feature should derive from System.Attribute For example:
// A custom attribute BugFix is assigned to the class and its members [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true) public class DeBugInfo : System.Attribute
In the above code, we have declared a class named DeBugInfo .
Let's build a custom feature named DeBugInfo Custom feature, which will store the information obtained by the debugger. It stores the following information:
The code number of the bug
The developer's name identifying the bug
The date of the last review of the code
A string message stored with the developer's tag
Our DeBugInfo The class will have three private properties (property) for storing the first three pieces of information and one public property (property) for storing messages. Therefore, the bug number, developer name, and review date will be the required positional parameters of the DeBugInfo class, and the message will be an optional named parameter.
Each feature must have at least one constructor. The required positional parameters should be passed through the constructor. The following code demonstrates DeBugInfo Class:}}
// A custom attribute BugFix is assigned to the class and its members [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true) public class DeBugInfo : System.Attribute { private int bugNo; private string developer; private string lastReview; public string message; public DeBugInfo(int bg, string dev, string d) { this.bugNo = bg; this.developer = dev; this.lastReview = d; } public int BugNo { get { return bugNo; } } public string Developer { get { return developer; } } public string LastReview { get { return lastReview; } } public string Message { get { return message; } set { message = value; } } }
To apply the attribute, place it immediately before its target:
[DeBugInfo(45, "Zara Ali", "12/8/2012", Message = "Return type mismatch")] [DeBugInfo(49, "Nuha Ali", "10/10/2012", Message = "Unused variable")] class Rectangle { // Member variables protected double length; protected double width; public Rectangle(double l, double w) { length = l; width = w; } [DeBugInfo(55, "Zara Ali", "19/10/2012" Message = "Return type mismatch")] public double GetArea() { return length * width; } [DeBugInfo(56, "Zara Ali", "19/10/2012)] public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); Console.WriteLine("Area: {0}", GetArea()); } }
In the next chapter, we will use the Reflection class object to retrieve this information.