C # Tutorial C # features (Attribute)

Source: Internet
Author: User

C # features (Attribute)

An attribute (Attribute) is a declarative label that is used to conduct information about the behavior of various elements (such as classes, methods, structures, enumerations, components, and so on) in a run-time delivery program. You can add declarative information to a program by using attributes. A declarative label is described by placing brackets ([]) in front of the element to which it is applied.

Attributes (Attribute) are used to add metadata, such as compiler directives and comments, descriptions, methods, classes, and other information. The. Net Framework provides two types of attributes: predefined and custom attributes.

Specified characteristics (Attribute)

The syntax for the specified attribute (Attribute) is as follows:

[Attribute (positional_parameters, name_parameter = value, ...)] Element

The name and value of the attribute (Attribute) is specified in square brackets before it is placed on the element it is applied to. Positional_parameters provides the necessary information, name_parameter the optional information.

Pre-defined features (Attribute)

The. Net Framework provides three predefined features:

AttributeUsage

Conditional

Obsolete

AttributeUsage

Pre-defined attributes AttributeUsage describes how to use a custom attribute class. It specifies the type of project to which the attribute can be applied.

The syntax for this attribute is defined as follows:

[AttributeUsage (   Validon,   allowmultiple=allowmultiple,   inherited=inherited)]

which

The parameter Validon specifies the language element to which the attribute 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 AllowMultiple property of the attribute. If true, the attribute is multi-purpose. The default value is False (single).

The parameter inherited (optional) provides a Boolean value for the inherited property of the attribute. If true, the attribute can be inherited by a derived class. 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 preprocessing identifier at the top of it.

It causes conditional compilation of method calls, depending on the specified value, such as Debug or Trace. For example, the value of a variable is displayed when debugging code.

The syntax for this attribute is defined as follows:

[Conditional (   Conditionalsymbol)]

For example:

[Conditional ("DEBUG")]

The following example shows the feature:

#define Debugusing 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 functionin function 1In function 2

Obsolete

This pre-defined attribute marks the program entity that should not be used. It lets you tell the compiler to discard a particular 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 (obsolete) by displaying a message that should use the new method instead of the old method.

The syntax for this attribute is defined as follows:

[Obsolete (   message)][obsolete (   message,   IsError)]

which

The parameter message, which is a string that describes why the item is obsolete and what the substitution uses.

The parameter, IsError, is a Boolean value. If the value is true, the compiler should treat the use of the project as an error. The default value is False (the compiler generates a warning).

The following example shows the feature:

Using System;public class myclass{   [Obsolete ("Don ' t use Oldmethod, use Newmethod instead", true)]   static void old Method ()   {       Console.WriteLine ("It's 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 gives a description of the error message:

Don ' t use the Oldmethod, use Newmethod instead

Create a custom attribute (Attribute)

The. Net framework allows you to create custom attributes that store declarative information and can be retrieved at run time. This information can be related to any target element, based on design criteria and application requirements.

Creating and using custom attributes consists of four steps:

Declaring Custom Attributes

Building Custom Attributes

Applying a custom attribute on the target program element

Accessing attributes by Reflection

The final step involves writing a simple program to read the metadata to find the various symbols. Metadata is data and information that is used to describe other data. The program should use reflection to access the attributes at run time. We will discuss this in more detail in the next chapter.

Declaring Custom Attributes

A new custom attribute should be derived from the System.Attribute class. 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 code above, we've declared a custom attribute named Debuginfo.

Building Custom Attributes

Let's build a custom attribute named Debuginfo that stores the information that the debugger obtains. It stores the following information:

Code number of the bug

Name of the developer who identified the bug

Date the last time the code was reviewed

A string message that stores the developer tag

Our Debuginfo class will have three private properties (property) for storing the first three information and a public property to store the message. So the bug number, developer name, and review date will be the required positional (positional) parameters of the Debuginfo class, and the message will be an optional named (named) parameter.

Each attribute must have at least one constructor. The required positional (positional) parameters should be passed through the constructor. The following code demonstrates the 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; }  }}

Apply a custom attribute

This feature is applied by placing the attribute before its target:

[Debuginfo ("Zara Ali", "12/8/2012", Message = "Return type Mismatch")] [Debuginfo, "Nuha Ali", "10/10/2012", Message = "Unused variable")]class rectangle{  //Member variable  protected double L Ength;  protected double width;  Public Rectangle (Double L, double W)  {      length = l;      width = w;  }  [Debuginfo ("Zara Ali", "19/10/2012",  Message = "Return type Mismatch")] public  double Getarea ()  {      return length * width;  }  [Debuginfo ("Zara Ali", "19/10/2012")]  public void Display ()  {      Console.WriteLine ("Length: {0}", length);      Console.WriteLine ("Width: {0}", width);      Console.WriteLine ("Area: {0}", Getarea ());}  }

The above is the "C # Tutorial" C # features (Attribute) content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.