Custom Attribute (original)

Source: Internet
Author: User

I. Theory

Attribute is translated into Attribute in msdn, which is not suitable for me. I prefer the title of the predecessor Wang Tao (author of <You must know. net>)-feature.

After reading the books of Wang Tao's predecessors, I remember that Wang Tao's predecessors described the features as follows: feature attribute is essentially a class that provides associated additional information for the target element,

In the runtime, the system obtains additional information through reflection. This is not comprehensive. However, there is not much time to find relevant information.

Ii. Example

0. Example scheme diagram

1. custom Attribute (DefaultAttribute. cs)

Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;

Namespace TestAttribute
{
Public class DefaultAttribute: Attribute
{
Public string DefaultName {get; set ;}
}
}

 

2. Use custom Attribute (Model. cs)

Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;

Namespace TestAttribute
{
Public class Model
{
[Default (DefaultName = "name")]
Public String name {get; set ;}

[Default (DefaultName = "")]
Public Byte Score {get; set ;}
}
}

3. Test button code (as shown below)

String modelpropertiesattributes = "";
Type t = typeof (Model );
PropertyInfo [] pis = t. GetProperties ();
Foreach (PropertyInfo pi in pis)
{
Modelpropertiesattributes + = (DefaultAttribute) pi. GetCustomAttributes (true) [0]). DefaultName + ":";
}
Modelpropertiesattributes = modelpropertiesattributes. Substring (0, modelpropertiesattributes. Length-1 );
MessageBox. Show (modelpropertiesattributes );

4. Test results (e.g)

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.