. NET attributes, attributes, and the difference between the two

Source: Internet
Author: User
Tags naming convention

The concept of characteristic (Attribute): The common language runtime allows the addition of a description declaration of a similar keyword, which labels elements in a program, such as classes, fields, methods, and so on, essentially a class. If there is no mechanism to get attribute additional information at run time, then there is no meaning to attribute. NET to implement additional information to obtain attribute at run time by reflection mechanism. So what exactly does the feature look like? For example, by adding [Obsolete ("This method declares to expired")] in front of the method, the ObsoleteAttribute is actually an attribute class in a. NET Framework assembly, "This method is declared expired" is to assign a value to the Message field in the ObsoleteAttribute class, and the ObsoleteAttribute class is defined in the assembly as follows:

Namespace System

{

public sealed class Obsoleteattribute:attribute

{

Public ObsoleteAttribute (String message);

}

}

Detailed feature descriptions and examples are described later.

the concept of property: attribute is the basic concept of object-oriented programming, provides access encapsulation of private fields, and implements the operation of a read writable property in C # with the get and set accessor methods, providing a secure and flexible data access encapsulation. So what does the property look like? Examples are as follows:

public class MyProperty

{

private string _name;

private int _age;

public string Name

{

get{Retuen _name;}

set{_name=value;}

}

public int Age

{

get{Retuen _age;}

set{_age=value;}

}

}

public class MyTest

{

public static void Main (string[] args)

{

MyProperty myproperty=new MyProperty ();

Triggering a set accessor

Myproperty.name= "Zhang Shan";

Trigger get accessor

String Name=myproperty.name;

}

}

the difference between characteristic (Attribute) and Attribute (property): through the clarification of concepts and the backtracking of history, we know that attributes and attributes are only in the name of the dispute, the other little relationship is not, The Chinese interpretation of attribute on MSDN is even a property, but I agree to address it as: feature. In terms of function and application, there is not too much fuzzy concept crossover, so there is no need to compare the similarities and differences of its application. One sentence is that it has two hairy relationships.

application scenarios and rules for features: I understand that the feature is the target element (which can be a dataset assembly, module modules, class classes, property properties, Method Methods, Fields field, Even function parameters param, etc.) add additional information, but can be initialized at compile time and obtained in reflection at run time. Custom features are mainly used in serialization, compiler directives, design patterns, and so on. rules for attributes:

Attributes are displayed in [,] form, placed next to each other, multiple attributes can be applied to the same element, and attributes are separated by commas, and the following expression rules are valid: [attributeusage][flags], [AttributeUsage, Flags], [flags, Attibuteusageattribute], [AttributeUsage (), Flagesattribute ()]. C # allows the specified prefix to represent the target element to which the attribute is applied, for example:

Using System;
Namespace Cx.net
{
[Assembly:myattribute (1)]//apply to Assembly
[Moduel:myattribute (2)]//Apply to Module
Pubic class Attributecx
{
//
}
}

Custom attribute types must be inherited directly or indirectly from the System.Attribute class, and the type must have a public constructor to create its instance.

All custom attribute names should have a attribute suffix (that is, the class name of the custom attribute must be xxxxattribute to end with attribute), which is a customary convention.

Custom features can also be applied to other custom features, which is also well understood, because the custom feature itself is a class that adheres to the public rules of the class.

Custom features do not affect any of the features of the application element, but only the qualities that the element has.

All non-abstract attributes must have public access restrictions.

Features are commonly used in compiler directives, breaking down # define, #undefine, #if, #endif的限制, and more flexible.

Custom features are often used to obtain code comment information at run time, with additional information to optimize debugging.

Custom features can be applied in certain design patterns, such as Factory mode.

Custom features are also commonly used for bit markers, unmanaged function tags, method discard tokens, and other aspects.

Five, the common characteristics of the description: common characteristics, that is. NET has been provided by the intrinsic characteristics, in fact. NET Framework has provided a wealth of inherent characteristics by us to play, the following highlights I think the most commonly used, the most typical of the inherent characteristics of a simple discussion, of course, this is only my opinion, but also insignificant.

1, AttributeUsage: The AttributeUsage attribute is used to control how custom attributes are applied to the target element. Examples are as follows:

AttributeTargets sets the range of features that can be used, whether AllowMultiple can be used multiple times on a target, whether the inherited attribute can be inherited to subclasses

  1. [AttributeUsage (Attributetargets.property, inherited = false, AllowMultiple = true)]
  2. public class Markattribute:attribute
  3. {
  4. Public Markattribute (string filedname, string description)
  5. {
  6. This .  Filedname = Filedname;
  7. This .  Description = Description;
  8. }
  9. private string _filedname;
  10. public string Filedname
  11. {
  12. get { return _filedname;}
  13. set {_filedname = value;}
  14. }
  15. private string _description;
  16. public string Description
  17. {
  18. get { return _description;}
  19. set {_description = value;}
  20. }
  21. }
  22. public class Test
  23. {
  24. Public Test ()
  25. {
  26. }
  27. private string _name;
  28. [Mark ("name", " ")]//Assign a value to a field in an attribute
  29. public string Name
  30. {
  31. get { return _name;}
  32. set {_name = value;}
  33. }
  34. }

2,Serializable: The serializable attribute indicates that the applied element can be serialized (serializated).

3,Conditional: The conditional attribute, used for conditional compilation, is used during debugging. NOTE: Conditional cannot be applied to data members and properties. There are other important features, including: Description, DefaultValue, Category, ReadOnly, browerable, etc.

Vi. A small example of obtaining characteristic (Attribute) information through a reflection mechanism:

Using System;
Using System.Reflection; Using reflection technology to obtain characteristic information

Namespace Anytao.net
{
         //custom features can also be applied to other custom features,
        & nbsp;//applies attributeusage to control how the newly defined features are applied
         [attributeusageattribute ( AttributeTargets.All,//can apply any element
         allowmultiple = true,//Allow application multiple times
    & nbsp    inherited = false)]//Do not inherit to a derived class
         //feature is also a class,
        The  //must inherit from the System.Attribute class, and the
         //naming convention is: class name +attribute.
         public class MyselfAttribute:System.Attribute
        &NBSP ; {
               //define fields
              &N Bsp private string _name;
                private int _age;
                private string _memo;

               //must define its constructor if no compiler is defined to provide a parameterless default constructor
                public myselfattribute ()
                {
&nbs P              }
                public Mysel Fattribute (string name, int age)
                {
      &NBS P                 _name = name;
                        _age = age;
               }

Defining properties
Obviously attributes and attributes are not the same thing.
public string Name
{
get {return _name = = null? string. Empty: _name; }
}

public int Age
{
get {return _age;}
}

public string Memo
{
get {return _memo;}
set {_memo = value;}
}

Defining methods
public void ShowName ()
{
Console.WriteLine ("Hello, {0}", _name = = null?) "World": _name);
}
}

Apply a custom attribute
You can use myself or Myselfattribute as the attribute name
You can assign a value to a property memo
[Myself ("Emma", +, Memo = "Emma is my good Girl.")] The first two are assigning values to the fields in the attribute, followed by assigning values to the attribute fields in the attribute
public class Mytest
{
public void SayHello ()
{
Console.WriteLine ("Hello, My.net World");
}
}

public class Myrun
{
public static void Main (string[] args)
{
How to determine attribute information with reflection
Type tp = typeof (Mytest); Get the System.Type type of mytest
MemberInfo info = TP; MemberInfo storing the reflected member information
Myselfattribute myattribute =
(Myselfattribute)   Attribute.GetCustomAttribute (Info, typeof (Myselfattribute)); Retrieving information about custom attributes (Myselfattribute) applied to the target element (MyTest Class)
if (myattribute! = null)
{

                           //Get the value of a custom attribute
                           console.writeline ("Name: {0}", M Yattribute.name);
                           console.writeline ("Ag") E: {0} ", myattribute.age);
                           console.writeline ("Me") Mo of {0} is {1} ", Myattribute.name, Myattribute.memo);
                           myattribute.showname ( );
                     }

Multi-point reflection
Object obj = Activator.CreateInstance (typeof (Mytest));

MethodInfo mi = TP. GetMethod ("SayHello");
Oil Invoke (obj, null);
Console.ReadLine ();
}
}
}

This sample code is excerpted from CSDN, author Neo_in_sap

. NET attributes, attributes, and the difference between the two

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.