Unity game Development--c# features attribute and automation

Source: Internet
Author: User

This article focuses on the use of attribute in C # and its possible application scenarios.

For example, your playing home's blood volume, attack, defense and other attributes written into the enumeration inside. Then the interface may have many places to get the description text of the property based on this enumeration.

For example, when you do the network framework, a protocol number corresponds to the processing of a class or a method.

For example, if you do an ORM, the properties of a class map the attributes in the persisted file, and what the past property names are.


1, what is attribute if used the Java annotation classmate, can take attribute as annotation to see. I don't know attribute's classmates. Don't worry, let's take a look at the official explanation:

the Attribute Class Associates predefined system information or user-defined custom information with a target element.A target element can be a assembly, class, constructor, delegate, enum, event, field, interface, method, portable EXE Cutable file module, parameter, property, return value, struct, or another attribute.

information provided by a attribute is also known as metadata.Metadata can examined at run time by your application to control how your program processes data, or before run Tim E by external tools to control how your application itself is processed or maintained. for example, the. NET Framework predefines and uses attribute types to control run-time behavior, and some programming Languages use attribute types to represent language features isn't directly supported by the. NET Framework Common Type Sys Tem.

All attribute types derive directly or indirectly from the attribute class. Attributes can applied to any target element; Multiple Attributes can is applied to the same target element; Tributes can inherited by an element derived from a target element.Use the AttributeTargets class to specify the target element to which, the attribute is applied.

the Attribute class provides convenient methods to retrieve and test custom attributes. apply Attributes and Use attributes to extend metadata . "Xml:space=" preserve ">for more information about using attributes, see  applying Attributes  and extending Metadata Using Attributes .

The attribute class can associate a target element with a predefined message or user-defined information. The target element here can be Assembly,class,constructor,delegate,enum,event,field,interface,method, executable module, Parameter,property,    Return value,struct or other attribute. The information provided by attribute is also known as metadata (metadata). Metadata can be used to control how your program data is accessed at run time, or to control how your program is handled or deployed before it runs through additional tools.    For example, the. NET Framework is predefined and uses attribute to control run-time behavior, and some programming languages use the attribute type to describe language attributes that are not directly supported by common types in the. NET Framework. All attribute types are inherited directly or indirectly from the attribute class. The attribute can be applied to any target element, multiple attribute can be applied to the same element, and the attribute class provides a traversal method to remove and test the custom attribute. For more information on attribute, you can see applying Attributes and extending Metadata Using Attributes.
If you look at the official explanation don't understand, read my translation also do not understand. It's OK ... Let's give an example to see what attribute can do. 2. Use attribute to bind enumerations and a descriptive text together, assuming this enumeration
public enum properties{//<summary>////    </summary>    HP = 1,    //<summary >//Physical Attack///    </summary>    phyatk = 2,//<summary>//    Physical Defense    //</summary >    phydef = 3,///    <summary> spell Attack///    </summary>    magatk = 4,    ///< summary>//Spell Defense///    </summary>    magdef = 5}
Note: If the code in Chinese is compiled with the error "Newline in constant". Then save the file's encoding as "UTF-8 with BOM". VS can be selected in "File"-"Advanced Save Options" and select the encoding dropdown.

Then you now want to follow the enumeration to get the Chinese description: For example, incoming:
Properties.magdef back to "spell defense".
The most primitive approach:
public class propertiesutils{Public    static string getdescbyproperties (Properties p)    {        switch (p)        { Case            PROPERTIES.HP:                return "blood volume";            Case PROPERTIES.PHYATK:                return "physical attack";            Case PROPERTIES.PHYDEF:                return "physical defense";            Case PROPERTIES.MAGATK:                return "spell attack";            Case PROPERTIES.MAGDEF:                return "spell defense";            Default:                return "Unknown attribute:" + P;}}    }

This can really solve the problem, but we can use attribute to do better. You can do a better job.
First define a attribute that stores the descriptive text.
[System.AttributeUsage (System.AttributeTargets.Field | System.AttributeTargets.Enum)]public class propertiesdesc:system.attribute{public    string Desc {get; private set; }}
Yes, it looks like it's easy.


Then we can add the Propertiesdesc defined above to the properties, like this:
public enum properties{    [Propertiesdesc ("Blood volume")]    HP = 1,    [Propertiesdesc ("Physical Attack")]    phyatk = 2,    [ Propertiesdesc ("Physical Defense")]    phydef = 3,    [Propertiesdesc ("Spell attack")]    magatk = 4,    [Propertiesdesc ("Spell defense")]    magdef = 5}
Ok. Thus, we are equivalent to associating a textual description information with our enumeration properties via attribute. So how to get it? Let's rewrite the previous Propertiesutils class.
public        Class propertiesutils{public static string Getdescbyproperties (Properties p) {Type type = P.gettype (); fieldinfo[] fields = type.        GetFields (); foreach (FieldInfo field) {if field. Name.equals (P.tostring ())) {object[] objs = field.                GetCustomAttributes (typeof (Propertiesdesc), true); if (OBJS! = null && OBJS. Length > 0) {return ((PROPERTIESDESC) objs[0]).                Desc;                } else {return p.tostring () + "No additional propertiesdesc information";    }}} return "No Such field:" +P; }}
Can see. There is no need to judge which enumeration value returns which string description. Instead, get the Propertiesdesc object for this enumeration field. It then returns the Desc property. Of course, you can also change the above code to generic and change the properties to a type so that you can handle all the enumerations. You can then add a cache to the location where you are looking for propertiesdesc. Cache according to the name of type and field. After the change, the code is as follows:
public class propertiesutils{private static Dictionary<type, dictionary<string, string>> cache = new Dict    Ionary<type, Dictionary<string, string>> ();        public static string Getdescbyproperties (object p) {var type = P.gettype (); if (!cache.        ContainsKey (type)) {Cache (type);        } var fieldnametodesc = Cache[type];        var fieldName = p.tostring (); Return Fieldnametodesc.containskey (fieldName)? Fieldnametodesc[fieldname]: String. Format ("Can not found such desc for field ' {0} ' in type ' {1} '", FieldName, type.    Name);        } private static void Cache (type type) {var dict = new dictionary<string, string> (); Cache.        ADD (type, dict); var fields = type.        GetFields (); foreach (var field in fields) {var objs = field.            GetCustomAttributes (typeof (Propertiesdesc), true); if (OBJS. Length > 0) {dict. ADD (field. Name, ((PropertieSDESC) objs[0]).            DESC); }        }    }}
3. What else can I do? Attribute too many things, such as you write a class, want to do ORM mapping, there are some fields do not want to map to the table, some want to map to the table. Some fields may not have the same name as the table field. You can then use attribute to identify which field needs to be mapped and which field to map to the database. Wait a minute.

Students who have done the network framework should also be familiar with an application, using attribute to do automatic message distribution.

In short, attribute can do a lot of automated things, it depends on how you use.










Unity game Development--c# features attribute and automation

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.