Attribute (C #) (from msdn)
Attributes are such members: they provide flexible mechanisms to read, write, or calculate private field values. Attributes can be used like public data members, but they are actually special methods called accessors. This allows data to be easily accessed while providing the security and flexibility of the method.
In this example, the class timeperiod stores a time period. Class stores time in seconds, but provides a property called hours, which allows the client to specify the time in hours. The accessors of the hours attribute perform the conversion between hours and seconds.
Example C # class timeperiod
{
Private double seconds;
Public double hours
{
Get {return seconds/3600 ;}
Set {seconds = value * 3600 ;}
}
}
Class Program
{
Static void main ()
{
Timeperiod T = new timeperiod ();
// Assigning the hours property causes the 'set' accessor to be called.
T. Hours = 24;
// Evaluating the hours property causes the 'get' accessor to be called.
System. Console. writeline ("time in hours:" + T. hours );
}
}
Output Time in hours: 24
Attribute overview attributes enable the class to get and set values in a public way, while hiding the implementation or verification code.
The get property accessors are used to return property values, while the set accessors are used to assign new values. These accessors can have different access levels. For more information, see accessors.
The value keyword is used to define the value allocated by the set indexer.
The attribute that does not implement the set method is read-only.
Usage attributes
Attributes combine multiple fields and methods. For users of the object, the attribute is displayed as a field, and the syntax for accessing this attribute must be identical. For the class implementer, the attribute is one or two code blocks, indicating a get accesser and/or a set accesser. When reading an attribute, run the get accessors code block. When a new value is assigned to the attribute, run the set accessors code block. Properties that do not have the set accessors are considered read-only. Attributes that do not have the get accessors are considered as write-only attributes. At the same time, the attributes of the two accessors are read/write attributes.
Unlike fields, attributes are not classified as variables. Therefore, attributes cannot be passed as REF (C # reference) parameters or out (C # reference) parameters.
Attributes have multiple usage features: they can verify data before they are allowed to be modified; they can transparently expose data on a class, which is actually from other sources (such as databases) retrieved; when data is changed, they can take actions, such as triggering an event or changing the values of other fields.
The attribute is declared in the class module by specifying the access level of the field, followed by the attribute type, followed by the attribute name, then, declare the get accesser and/or set accesser code modules.