"C # Advanced Series" 17 feature attribute

Source: Internet
Author: User

Some of this stuff is called custom features, but I like to call features directly, but in that case some people don't know what I'm talking about, and if I say it's attribute then I know it or use it.

Remember the chapter on enumeration and bit flags, about bit flags, and the use of a [flags].

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

The ComVisible and flags here are features.

The role of properties

Features can be declared to add annotations to their code constructs for special functions. It is equivalent to writing additional information into the metadata table, which enables queries to be made at runtime to query for these additional information, thus dynamically altering how the code executes.

(In fact, the attribute is serialized to the metadata table after it is compiled, and then deserialized to the instance when it is obtained.) )

For example, the following examples:

    • The DllImport attribute can be applied to a method that tells the CLR that the implementation of the method resides in the unmanaged code of the specified DLL.
    • The serializable attribute can be applied to a type, telling the serialization formatter that a field of an instance can be serialized and deserialized.
    • The AssemblyVersion attribute can be applied to an assembly, setting the assembly's version number.
    • The flags attribute is applied to the enumeration type, and the enumeration type becomes a set of bit flags.

Application of properties

The simple way to apply it is to place the attribute in a square bracket before the target element.

When you apply an attribute, C # allows you to explicitly specify the target element to which the attribute is to be applied with a prefix.

[Type:someattr]//Apply to type     Public classpeople<[typevar:someattr]t> {//Apply to generics[Field:someattr]//Apply To Fields         PublicInt32 age; [return: SomeAttr]//apply to return value[Method:someattr]//Apply to Method         PublicInt32 Eat ([param:someattr]//Apply to ParametersString Foodname) {            return 1; } [Property:someattr]//Apply to Properties         PublicString Someprop {[method:someattr]//apply to accessor methods            Get{return NULL; } }        [Event: SomeAttr]//Apply to Event[Field:someattr]//fields that are applied to compiler builds[Method:someattr]//Add and remove methods that are applied to the compiler generation         Public EventEventHandler dieevent; }

Of course there are more assembly and modules that are applied to the assembly and module respectively.

An attribute is actually an instance of a class. Attribute classes must derive directly or indirectly from the public abstract class System.Attribute. For example, the [Flags] feature actually defines its attribute class as FlagsAttribute, except that C # allows the application of attributes to omit attribute to simplify the code.

There is also a special syntax for the application of attributes:

[DllImport ("Kernel32", charset=charset.auto,setlasterror=true)]

The named DllImportAttribute class has only one constructor that accepts a string argument, but the above application not only provides a string parameter, but also gives two more parameters. In fact, the above syntax "Kernel32" is called the positional parameter , it is mandatory, and the other two parameters called named Parameters , its role is to allow in the constructed attribute object to set any public fields and properties of the object.

You can also use multiple attributes in one square bracket

[Someattr,anotherattr]

Definition of attributes

Now let's set a feature.

[AttributeUsage (attributetargets.class,allowmultiple =false, inherited =false)]//This attribute is used to limit the people attribute to the class only, if not added by default is unlimited. The next two properties are not allowed to specify the people attribute more than once for an element, and the people attribute of the element is not inherited     Public classPeopleAttribute:System.Attribute {//here the class name suffix attribute is to meet the standards of Microsoft, of course, can not add        Private string_sex;  PublicPeopleattribute () {} Public stringSex {Get{return_sex;} }    }

The feature should be simple enough, because the feature is really just an identification function that records additional information for some classes, rather than writing some very complex code inside.

The type of the attribute's fields and properties is also simple, only with primitive types, type, and enum types. (one-dimensional 0 cardinality groups can also be used, but should be avoided as much as possible.) )

Detection characteristics

Usually the characteristics are played with reflection, because it is generally reflected to detect the existence of the feature, or to obtain information about the characteristics. (I remember when I wrote the ORM myself, I used reflection and character)

typeof (FileAttributes). IsDefined (typeoffalse); // used to determine if the [Flags] attribute is applied to the FileAttributes class, and the answer is, of course, true.

However, this is only for the detection of characteristics, in fact, we are more time to obtain some properties of the information, then we need to get the attribute instance object.

Object typeof (FileAttributes). GetCustomAttributes (typeoffalse);

The above two examples are the methods defined in the System.Reflection namespace for each type of class (such as: Assembly,memberinfo,fieldinfo, etc.), each of which provides isdefined and GetCustomAttributes methods.

Another is System.Reflection.CustomAttributeExtensions. This static class also provides a number of static methods to detect and better to use. Where GetCustomAttributes directly returns attribute[] instead of the previous object[].

Detection attribute (does not create an object derived from attribute)

The previous detection methods, in addition to isdefined, invoke the constructor of the attribute class internally, and may also invoke the get and set accessor methods of the property. The type constructor is also called if it is the first access type.

In these methods or constructors, there is a security risk if there is code to execute every time the lookup attribute is executed. (So if the feature class is simple enough, you don't actually need to use this detection feature)

So with the System.Reflection.CustomAttributeData class, it is forbidden to execute code in the attribute class when looking for attributes.

Matching two instances of a feature

System.Attribute overrides the Equals method of object, which compares the types of two objects internally. Inconsistencies return false, and consistent uses reflection to compare the values of the fields in two attribute objects (calling equals for each field). All fields match to return true otherwise false.

You can override equals in your own defined attribute class to remove the use of reflection to improve performance. (Remember to rewrite GetHashCode when overriding equals)

System.Attribute also exposes the virtual method match, whose default implementation simply calls Equals and returns the result, but we rewrite it to achieve more matching effects.

Conditional attribute Class

The System.Diagnostics.ConditionalAttribute attribute class is called a conditional attribute class.

#define Troytest
[Conditional ("troytest"), Conditional ("Verify")]      Public class PeopleAttribute:System.Attribute {        public  Peopleattribute () {                    }    }

Then now if the people attribute is applied to an element such as a class man, then the attribute information is written to the man's metadata only if the troytest or verify symbol is defined. (However, the definition metadata and implementation of the people class is still in the assembly, after all, it is a class that simply does not write additional information to the man's metadata)

#define Test This syntax is written at the top of the file, which is the using above.

Reference # # Usage Location: https://msdn.microsoft.com/zh-cn/library/yt3yck0x.aspx

Ps:

These two days changed a set of blog skin, oneself also wrote part of Style, the most 6 is to take the drawing tool to change two Ali picture.

Look at the effect, feeling still quite a sense of accomplishment.

"C # Advanced Series" 17 feature attribute

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.