Attribute Usage Details

Source: Internet
Author: User

Note:Attribute translation is a feature, and property translation is a property. I have read many online articles from this blog. I will not list them one by one, but I would like to express my gratitude to those bloggers.

 

Attributes is a new description. We can use attributes to define the design period information (such as the help file and the URL of the document) and attributes to define the runtime information (such, associate the elements in XML with the member fields of the class ). You can also use attributes to create a "self-description" component. Attribute is very similar to annotation in Java.

 

1,C # attributeusage has three attributes:
Validon: defines the program entity to be placed before, such as attributetargets. Class. Other possible values include:

AttributeTargets.AllAttributeTargets.AssemblyAttributeTargets.StructAttributeTargets.EnumAttributeTargets.ConstructorAttributeTargets.MethodAttributeTargets.PropertyAttributeTargets.FieldAttributeTargets.EventAttributeTargets.InterfaceAttributeTargets.ParameterAttributeTargets.Delegate

Allowmultiple: defines whether a feature can be placed multiple times before the same program entity.

Inherited: whether a feature can be inherited

 

2,Instance used:

[AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)]public class HelpAttribute: DescriptionAttribute{   public HelpeAttribute(string desc): base(desc) {  }    ...}public class Test{   [Help("test attribute")]   public string TestAttribute { get;set; }}

 

3,Predefined attribute
For example, the obsolete features:

[Obsolete("Old method, don't use", true]public void oldMethod() { }

It indicates that this is an obsolete method and should not be used. The second parameter is true, indicating that a compilation error will occur if you have to use it.

 

4,Feature parameters
Feature parameters can be either mandatory or optional.

Mandatory feature parameters are passed through the constructor of the feature class.

Optional feature parameters are different. View instances:

[Attributeusage (attributetargets. class, allowmultiple = false, inherited = false] public class helpattriple: attribute {public helpattribute (string DESC) // force parameter {This. desription = DESC; this. version = "No version defined"; // optional parameter} Public String description {Get;} Public String version {Get; set ;} // optional parameter. If this parameter can be set, setter is required}

Then there is the following code:

[Help("ClassA")][Help("ClassB", Version="1.0")]

The version parameter of the first line is the default "No version defined", and the version parameter of the second line of code is 1.0

 

5,Parameter types of feature classes

The parameter types of the feature class are limited to one of the following types:

Bool, byte, Char, double, float, Int, long, short, String, system. type, object, enumeration type

 

6,Feature mark
How do I bind a feature to an assembly? How can I bind it to the return type of a method?

We can use feature tags, such:

[assembly: Help("blabla")]

This feature flag tells the compiler help feature to be bound to the entire assembly. Possible identifiers include:

assembly、module、type、method、property、event、field、param、return

Instance code:

using System; using System.Reflection; using System.Diagnostics; //attaching Help attribute to entire assembly [assembly : Help("This Assembly demonstrates custom attributes creation and their run-time query.")] //our custom attribute class public class HelpAttribute : Attribute {   // ...     }

7,View attribute during runtime

Through reflection, the code example is as follows, which is easy to explain:

1. query the feature information in the Assembly:

HelpAttribute HelpAttr; //Querying Assembly Attributes String assemblyName; Process p = Process.GetCurrentProcess(); assemblyName = p.ProcessName + ".exe"; Assembly a = Assembly.LoadFrom(assemblyName); foreach (Attribute attr in a.GetCustomAttributes(true)) {   HelpAttr = attr as HelpAttribute;    if (null != HelpAttr)    { 
Console.WriteLine("Description of {0}:\n{1}",assemblyName,HelpAttr.Description);    } }

Ii. query the feature information of classes, methods, and attributes:

Type type = typeof(AnyClass); HelpAttribute HelpAttr; //Querying Class Attributes foreach (Attribute attr in type.GetCustomAttributes(true)) {    HelpAttr = attr as HelpAttribute;    if (null != HelpAttr)    {       Console.WriteLine("Description of AnyClass:\n{0}", HelpAttr.Description);    } } //Querying Class-Method Attributes   foreach(MethodInfo method in type.GetMethods()) {    foreach (Attribute attr in method.GetCustomAttributes(true))    {      HelpAttr = attr as HelpAttribute;       if (null != HelpAttr)       {         Console.WriteLine("Description of {0}:\n{1}",  method.Name,  HelpAttr.Description);        }     } } //Querying Class-Field (only public) Attributes foreach(FieldInfo field in type.GetFields()) {    foreach (Attribute attr in field.GetCustomAttributes(true))    {      HelpAttr= attr as HelpAttribute;       if (null != HelpAttr)       {          Console.WriteLine("Description of {0}:\n{1}", field.Name,HelpAttr.Description);        }     }}

8,Another instance (application with reflection)

Public class exceltemplatemodel {[description ("city")] Public String city {Get; set;} [description ("company industry")] Public String companyindustry {Get; set ;} [description ("company name")] Public String companyName {Get; Set ;}....} propertyinfo [] properties = typeof (exceltemplatemodel ). getproperties (). where (C => C. getcustomattributes (typeof (descriptionattribute), false ). length> 0 ). tolist (); For (INT I = 0; I <propertys. count; I ++) {exceltemplatemodel item = new exceltemplatemodel (); properties [I]. setvalue (item, value, null); excellist. add (item );}

For other details, see: http://msdn.microsoft.com/en-us/library/e8kc3626.aspx

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.