I have been working for more than two months. I took a few days off and made up for 10 days to schedule a trip for myself. Although it was an afternoon flight, I couldn't sleep in the early morning, after running up and packing up, no sleep. so .. with this blog
I believe that many beginners, like me, often see the following:Code
For the things marked by the red lines in the graph, you can refer to the materials to learn the attribute ). as a result, Google and Baidu seem to have a lot of blog posts on this topic, and it is estimated that they are still in the fog after reading it. OK... the monks will take the liberty to try to learn attribute in the simplest way.
1,What is attribute?
Don't look at the large text descriptions first. Attribute Translation: (Baidu translation is recommended. Good...The following translation results are referenced in the Baidu dictionary.)
Attribute1
TermN. [C]
2.(Person,Things,Title)Flag,Symbol
Yes, attribute is not complex. If this mark is used, this stuff (class and field) is regarded as a sign and a symbol. There is nothing complicated, just as we shop in a supermarket and there is a bar code attribute on the product.
Some may ask, for example, why does a bar code not use an attribute to describe a commodity? (See the difference between attributes and attributes.)
Here, we will combine the official documents, in plain words:
You can use attribute to add some additional information to some target elements (such as classes, fields, and interfaces ),ProgramDuring compilation, the additional information is serialized into the Assembly metadata. When you run the program, you can use the reflection technology to read the additional information from the Assembly metadata,Determine the behavior of your program based on the additional information..
2. Differences between attributes and attributes
Do not consider so much. It is not necessary to record these two items. OK... The following describes how to learn using code.
3. Use the attribute defined by. net
Create a console project demo and create a new myclass class
Myclass
Public Class Myclass
{
[Obsolete ( " This is an old method. Please call the new method newmethod " )]
Public Void Oldmethod ()
{
Console. writeline ( " This is the old method " );
}
[Obsolete ( " This is an old method. Please call the new method newmethod " , True )]
Public Void Oldmethod1 ()
{
Console. writeline (" This is the old method " );
}
Public Void Newmethod ()
{
Console. writeline ( " This is a new method " );
}
}
We compile the code to call the myclass class in program.
Call myclass
Myclass =NewMyclass ();
Myclass. oldmethod ();
Myclass. oldmethod1 ();
Console. readkey ();
At this time, we compile the demo project and find warnings and errors.
Isn't it amazing why the compiler can handle custom features such as obsolete in methods, such as warning messages when using methods marked with the obsolete feature, but what will the compiler do if we customize the attribute?
4. custom attribute
1. comment out the program to call the test code of the myclass class. Create a new class named myfirstattribute .(The class name must be xxxattribute. The reason is :)
The defined attribute is required.Derived directly or indirectly from the public abstract class system. Attribute. Therefore, obsolete, stathread, and serializable are derived from attribute.
The naming rule for custom attribute is"Feature name + attribute".
Myfirstattribute
ClassMyfirstattribute: attribute
{
Public StringMSG {Get;Set;}
PublicMyfirstattribute (StringMSG)
{
MSG = MSG;
}
}
Add a new class person in the demo project. Use the custom myfirstattribute class to apply it to this class.
Person
[Myfirstattribute ("Customize the first attribute")]
ClassPerson
{
}
After we use the custom myfirstattribute tag for the person class, how can the program obtain the myfirstattribute content of the person? Compile the test code in the program class
Get custom getcustomattributes
VaRAttributes =Typeof(Person). getcustomattributes (Typeof(Myfirstattribute ),True);
Myfirstattribute myattribute = attributes [0]AsMyfirstattribute;
If(Myattribute! =Null)
{
Console. writeline (myattribute. msg );
}
Compile and run the demo project and run the program.
At this point, we have customized a myfirstattribute and successfully called and tested it. looking back at this simple code, we will find a model, that is, we have customized an attribute class, when applied to the target element (class, field, interface, etc ), when we write a program to get (reflection) the target element, We parse our attribute class and then implement the attribute function code.
For example, I want to achieve this effect:We put a custom tag on the attributes of the person class. When using the custom tag attribute, the custom tag is used when the person object is written to a file, save it to the file. otherwise, it will not be saved.
OK. First define an attribute (Note: naming rules and inheritance relationships)
View code
ClassWritefileattribute: attribute
{
}
Add several property codes in the person class and use the tag
Person
Class Person
{
[Writefile]
Public Int Id { Get ; Set ;}
[Writefile]
Public String Name { Get ; Set ;}
/// <Summary>
/// Password, without Mark
/// </Summary>
Public String PWD { Get ; Set ;}
[Writefile]
Public Int Age { Get ; Set ;}
}
Then we compile the code for calling the person class in the program.
Writefileattribute
Person Per1 =New Person () {age = 20 , Id = 1 , Name = " Winloa " , Pwd = " 123 " };
Stringbuilder content = New Stringbuilder ();
// Analyze the attributes in person that use writefileattribute. If writefileattribute is used, write the attribute value to the file.
Type typeperson = per1.gettype ();
Propertyinfo [] proparry = typeperson. getproperties ();
Foreach ( VaR Item In Proparry)
{
Object [] OBJ = item. getcustomattributes ( Typeof (Writefileattribute ), False );
If (Obj. length> 0 )
{
// This attribute is marked with writefileattribute.
Content. append (item. Name + " \ T " + Item. getvalue (Per1, Null ) + " \ R \ n " );
}
}
File. writealltext ( " D: \ attribute.txt " , Content. tostring ());
Then we compile and run the demoproject. We found that there is an attribute.txt file under the ddisk root directory.
The PWD attribute in the person class does not use writefileattribute, so it is not recorded when it is saved to a file.
5. Summary
In general, attribute is a tag. These tags are provided by the. NET system. We can also customize them. The custom attribute class shouldNote: naming rules and inheritance relationships
Then we use a custom attribute class and should have a Response Parsing class. Otherwise, the custom attribute program does not know how to call it.
For example, we want to persist the previous person class objects to the database (the primary key and database compatibility should be considered here)
1. customize an attribute ---> writedatabaseattribute. CS
2. Use writedatabaseattribute in person
3. Write a parsing writedatabaseattribute class to complete the database crud in writedatabaseattribute