[C # advanced series] 17 feature Attribute,

Source: Internet
Author: User

[C # advanced series] 17 feature Attribute,

Some of these are called custom features, but I like to call them features directly, but some people do not know what I am talking about, if I say "Attribute", I will understand what I know or have used.

Remember to refer to the enumeration and bits chapter. There is a [Flags] usage for bits.

    [ComVisible(true)]    [Flags]    public enum FileAttributes    {        /***/    }

Here ComVisible and Flags are features.

Features

You can use features to add annotations for your own code structures to implement special functions. It is equivalent to writing additional information to the metadata table so that the additional information can be queried at runtime, thus dynamically changing the Code Execution Mode.

(In fact, after compilation, the feature is serialized to the metadata table and then deserialized into an instance upon retrieval .)

For example:

  • The DllImport feature can be applied to methods to tell CLR that the implementation of this method is in the unmanaged code of the specified DLL.
  • The Serializable feature can be applied to types to tell the serialization formatter that the fields of an instance can be serialized or deserialized.
  • The AssemblyVersion feature can be used to set the version number of an assembly.
  • The Flags feature applies to enumeration types, and the enumeration type becomes a bit flag set.

Application of features

The application method is simple, that is, placing features in a pair of square brackets before the target element.

When using features, C # allows you to use a prefix to specify the target elements that a feature applies.

[Type: SomeAttr] // applies to public class People <[typevar: SomeAttr] T> {// applies to generic [field: SomeAttr] // applies to public Int32 age; [return: SomeAttr] // apply to return value [method: SomeAttr] // apply to public Int32 Eat ([param: SomeAttr] // apply to String foodName) {return 1 ;} [property: SomeAttr] // applies to the public String SomeProp {[method: SomeAttr] // applies to the accessor method get {return null;} [event: someAttr] // applies to the event [field: SomeAttr] // applies to the [method: SomeAttr] field generated by the compiler. // applies to the add and remove methods generated by the compiler. public event EventHandler DieEvent ;}

Of course, the above assembly and module are applied to the assembly and module respectively.

A feature is actually an instance of a class. Feature classes must be derived directly or indirectly from the public abstract class System. Attribute. For example, the [Flags] feature actually defines its feature class as FlagsAttribute, except that Attribute is omitted when C # allows the application feature to simplify code.

Feature applications also have a special Syntax:

[DllImport("Kernel32",CharSet=CharSet.Auto,SetLastError=true)]

The name of the DllImportAttribute class has only one constructor that accepts a String parameter. However, the preceding application not only provides a String parameter, but also provides two parameters. In fact, in the above syntax"Kernel32"CallPositioning parametersIt is mandatory, and the other two parameters are calledNaming ParametersIt allows you to set any public fields and attributes of an object in a constructed property object.

You can also use multiple features in one square brackets.

[SomeAttr,AnotherAttr]

Feature Definition

Now let's determine a feature

[AttributeUsage (AttributeTargets. class, AllowMultiple = false, Inherited = false)] // This feature is used to limit the People feature to Class only. If this feature is not added, it is unlimited by default. the following two attributes are not allowed to specify the People attribute for an element multiple times, and the People attribute of the element is not inherited from the public class PeopleAttribute: System. attribute {// here, the class name is followed by the suffix Attribute to comply with Microsoft's standards. Of course, you can also not add private string _ sex; public PeopleAttribute () {} public string Sex {get {return _ sex ;}}}

The feature should be simple enough, because the feature is actually only an identifier, recording additional information of some classes, rather than writing some complicated code into it.

The field and attribute Type of the feature are also very simple. Only the primitive Type, Type and enumeration Type can be used. (You can also use a one-dimensional 0-base array, but avoid it as much as possible .)

Detection features

Features are usually used together with reflection, because reflection is generally used to detect the existence of features or to obtain feature information. (I remember when I wrote my own ORM, I used reflection to add features)

Typeof (FileAttributes). IsDefined (typeof (FlagsAttribute), false); // determines whether the [Flags] attribute is applied to the FileAttributes class. The answer is true.

However, this is only used to detect features. In fact, we need to obtain some attribute information in the features, so we need to obtain the feature instance object.

object[] arr= typeof(FileAttributes).GetCustomAttributes(typeof(FlagsAttribute), false);

The two examples above are the methods defined by the System. Reflection namespace for each type (such as Assembly, MemberInfo, FieldInfo). Each class provides the IsDefined and GetCustomAttributes methods.

Another static class is System. Reflection. CustomAttributeExtensions. It also provides a batch of static methods for detection and is easier to use. GetCustomAttributes directly returns Attribute [] instead of the previous Object [].

Detection features (do not create objects derived from Attribute)

In addition to IsDefined, the previous Detection Methods call the constructor of the feature class internally, and may also call the Get and set accessors of the attribute. If it is the first access type, the Type constructor is also called.

In these methods or constructor, if there is code to be executed for each search feature, there will be a security risk. (If the feature class is simple enough, this detection feature is not required)

Therefore, with the System. Reflection. CustomAttributeData class, the code in the feature class cannot be executed during feature search.

Matching of two feature instances

System. Attribute overrides the Equals method of the Object and compares the types of the two objects internally. Otherwise, false is returned. Reflection is used to compare the field values of the two feature objects (Equals is called for each field ). If all fields match, true is returned. Otherwise, false is returned.

You can override Equals in your own defined feature class to remove reflection usage, thus improving performance. (Remember to rewrite GetHashCode when rewriting Equals)

System. Attribute also exposes the virtual method Match. Its default implementation is to call Equals and return results. However, we can rewrite it to achieve more matching effects.

Condition features

The System. Diagnostics. ConditionalAttribute feature class is called the condition feature class.

#define TroyTest
[Conditional("TroyTest"), Conditional("Verify")]    public class PeopleAttribute:System.Attribute {        public PeopleAttribute() {                    }    }

Now, if the People feature applies to an element such as a Man class, after compilation, only when the TroyTest or Verify symbol is defined, to write feature information to Man's metadata. (However, the definition metadata and Implementation of The People class are still in the Assembly. After all, it is a class, but it does not write additional information to Man's metadata)

# Define Test: the syntax should be written at the top of the file, that is, over using.

Reference # define location: https://msdn.microsoft.com/zh-cn/library/yt3yck0x.aspx

 

PS:

In the past two days, I changed my blog skin and wrote some styles. The sixth one was to use the drawing tool to change two pictures of a raccoon.

After looking at the effect, I feel quite fulfilled.

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.