Home > Article > Backend Development > [c# tutorial] C# attributes (Attribute)
C# Attributes
Attributes are declarative tags used to convey behavioral information of various elements in the program (such as classes, methods, structures, enumerations, components, etc.) at runtime. You can add declarative information to your program by using attributes. A declarative tag is described by square brackets ([ ]) placed in front of the element to which it applies.
Attributes are used to add metadata, such as compiler instructions and comments, descriptions, methods, classes and other information. The .Net framework provides two types of attributes: predefined attributes and custom attributes.
Specify attributes (Attribute)
The syntax for specifying attributes (Attribute) is as follows:
[attribute(positional_parameters, name_parameter = value, ...)] element
The name and value of an attribute (Attribute) are specified within square brackets, placed before the element to which it applies. positional_parameters specifies required information, name_parameter specifies optional information.
Predefined attributes (Attribute)
.Net framework provides three predefined attributes:
AttributeUsage
Conditional
Obsolete
AttributeUsage
Predefined attribute AttributeUsage describes how to use a custom attribute class. It specifies the types of items to which the feature can be applied.
The syntax for specifying this feature is as follows:
[AttributeUsage( validon, AllowMultiple=allowmultiple, Inherited=inherited )]
Where:
The parameter validon specifies the language element in which the feature can be placed. It is a combination of the values of the enumerator AttributeTargets. The default value is AttributeTargets.All.
The parameter allowmultiple (optional) provides a boolean value for the feature's AllowMultiple property. If true, the attribute is multipurpose. The default value is false (single use).
The inherited parameter (optional) provides a boolean value for the Inherited property of this feature. 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.Feild | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)]
Conditional
This predefined attribute marks a conditional method whose execution depends on the preprocessor identifier it tops.
It will cause conditional compilation of method calls, depending on the specified value, such as Debug or Trace. For example, display the value of a variable when debugging code.
The syntax that specifies this feature is as follows:
[Conditional( conditionalSymbol )]
For example:
[Conditional("DEBUG")]
The following example demonstrates this 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 produces the following results:
In Main function In Function 1 In Function 2
Obsolete
This predefined attribute marks program entities that should not be used. It lets you tell 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 by displaying a message that the new method should be used instead of the old method. of).
The syntax that specifies this feature is as follows:
[Obsolete( message )] [Obsolete( message, iserror )]
Where:
The parameter message is a string describing why the project is obsolete and what to use instead.
The parameter iserror is a Boolean value. If this value is true, the compiler should treat the use of this item as an error. The default value is false (the compiler generates a warning).
The following example demonstrates this 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 this program, the compiler will give an error message stating:
Don't use OldMethod, use NewMethod instead
Create a custom attribute (Attribute)
.Net framework allows the creation of custom Attributes are used to store declarative information that can be retrieved at runtime. This information can be associated with any target element based on design criteria and application needs.
创建并使用自定义特性包含四个步骤:
声明自定义特性
构建自定义特性
在目标程序元素上应用自定义特性
通过反射访问特性
最后一个步骤包含编写一个简单的程序来读取元数据以便查找各种符号。元数据是用于描述其他数据的数据和信息。该程序应使用反射来在运行时访问特性。我们将在下一章详细讨论这点。
声明自定义特性
一个新的自定义特性应派生自 System.Attribute 类。例如:
// 一个自定义特性 BugFix 被赋给类及其成员 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)] public class DeBugInfo : System.Attribute
在上面的代码中,我们已经声明了一个名为 DeBugInfo 的自定义特性。
构建自定义特性
让我们构建一个名为 DeBugInfo 的自定义特性,该特性将存储调试程序获得的信息。它存储下面的信息:
bug 的代码编号
辨认该 bug 的开发人员名字
最后一次审查该代码的日期
一个存储了开发人员标记的字符串消息
我们的 DeBugInfo 类将带有三个用于存储前三个信息的私有属性(property)和一个用于存储消息的公有属性(property)。所以 bug 编号、开发人员名字和审查日期将是 DeBugInfo 类的必需的定位( positional)参数,消息将是一个可选的命名(named)参数。
每个特性必须至少有一个构造函数。必需的定位( positional)参数应通过构造函数传递。下面的代码演示了 DeBugInfo 类:
// 一个自定义特性 BugFix 被赋给类及其成员 [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; } } }
应用自定义特性
通过把特性放置在紧接着它的目标之前,来应用该特性:
[DeBugInfo(45, "Zara Ali", "12/8/2012", Message = "Return type mismatch")] [DeBugInfo(49, "Nuha Ali", "10/10/2012", Message = "Unused variable")] class Rectangle { // 成员变量 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()); } }
以上就是【c#教程】C# 特性(Attribute)的内容,更多相关内容请关注PHP中文网(www.php.cn)!