Attribute is a class first. in C #, attribute is processed as a compiler instruction.
In. net, attributes play a very important role. Whether it is writing Web controls or Web Services, attributes play an indispensable role, while serialization.ProgramThe installation features are even more inseparable from the attributes and seem mysterious. In fact, it is not difficult to write a property of your own. There are similar examples in codeproject and C # corner.Code. Below is only a common attribute. If it is AOP, it must be inherited from contextattribute. For AOP and contextattributeArticleThe Code project will also provide relevant examples.
Using system;
Namespace Test
{
// Only allow this attribute to be added to Classes
[Attributeusage (attributetargets. Class)]
Public class testattribute: attribute
{
// A number with some imaginary importance
Public int thenumber;
// A string that cocould be useful somewhere
Public string name;
// The only constructor requiring that
// thenumber be set
Public testattribute (INT thenumber)
{< br> This. thenumber = thenumber;
name = "NONE";
}
// method to assign strate that an attribute is really just
// a class at heart. this will be used in driver. CS
Public void printout ()
{< br> console. writeline ("/tthenumber = {0}", thenumber);
console. writeline ("/tname =/" {0}/"", name);
}< BR >}< br> the above is an attribute class, it is very easy to note that the attributeusage attribute must be added before the attribute class. The attributetargets in it defines the application scope of this attribute. For example, it is only applicable to methods or classes, in the above Code, setting this attribute can only be used by the class
you can use your own attribute in your class, for example,
[test (4, name = "testclassb")]
public class testmyatt
{}< br> after careful consideration, the thenumber attribute must be initialized in the construction method of the testattribute class. Therefore, when using testattribute, there must be an integer, and the name can be dispensable based on the actual situation
it is actually very useful to implement your own attributes, I personally think it is of great benefit to implement the AOP mode.