Search C # (attribute 3) C # Talent Bird (QQ: 249178521)
8. Static attribute
l Static attribute is to contact the class
Ø can only be used by class name
Sealed Class Error
{
...
Public Static Textwriter log
{
Get {return log;}
}
...
Private Static Street Sink
= New FileStream ("Error.log", FileMode.Append);
Private static textwriter log
= New streamwriter (SINK);
}
Error.log.writeline ("Time Out");
The field can be static, so attributes can also be static. The grammar of the static attribute is very simple, as long as the Static keyword is added to the attribute name. The mechanisms and restrictions in the static function are equally applicable to static properties. Static attributes can be represented as read-only or only written as usual properties.
Static properties have no implied this parameters. For example, in the above example, the Log This static property can access the Log this field because the log is a static field. If the log is an instance field, then logs cannot be accessed. E.g:
Public Sealed Class Error
{
Public Static Textwriter log
{
Get {return log;}
}
Private stream sink = ...
Private textwriter log = ...
}
9. Attribute vs. field
l Comparison of properties and fields:
Ø Attributes cannot use REF / OUT type parameters
Ø You must assign values before use
//Attributes
Struct Time
{
...
Public int hour
{
Set {...}
}
Private int hour;
}
Time lunch;
Method (Out Lunch. Hour); // Error
Lunch.Hour = 12; // Error
// field
Struct Time
{
...
Public int hour;
...
}
Time lunch;
Method (Out Lunch. Hour); / / correct
Lunch.Hour = 12;
The property must be assigned before use, for example:
Time lunch;
Lunch.Hour = 12; // Error, Lunch has no initialization
10. Properties vs. function
l
Ø all contain execution code
Ø Access modifiers
Ø You can have Virtual, Abstract, Override modifier
Ø can be used in the interface
l Different points
Ø Property can only have a GET / SET statement
Ø Attributes can not be VOID type
Ø Attributes cannot use parameters
Ø Attributes cannot be used [] parameters
Ø Attributes can not use parentheses