C # Advanced Road --C # class attributes and methods
basis:
1, the role of attributes: protection field, and the field value to be assigned is defined
Attributes |
public class field which corresponds to c # property exposed to the outside, but it is different from the ordinary field attribute field just outside of the package, without any of its content, the method similar returned. Still need to set up internal fields. private class field corresponding to fields of the inner classes. Accessor properties can be viewed as private variables. |
2, the use of the property:
grammar |
|
3, field names and format attributes:
Naming fields commonly used: _cameCase
Naming fields commonly used: PascalCase
4, after the property had often to access the field through the property.
Properties are typically declared as public, fields are often declared as private.
Field external access class, are achieved through the property. g
et of values can be defined set of assignments can be defined, generally we will get called and set accessor.
5, is divided into four kinds of attributes,
1) both read and write: contains both get and set
2) Read Only: Contains only get
3) Write Only: Contains only set
4) automatic properties
Examples |
|
method: |
"Method" code block comprising a series of statements. |
In C #, each of the instruction execution is done in the context of a method. Method declared in the class or structure. When you declare, you need to specify when declaring the access level, return values, method name, and any method parameters. Method parameter in parentheses and separated by commas. Empty parentheses method takes no parameters. |
Class contains the following three methods: |
class Motorcycle { public void StartEngine() { } public void AddGas(int gallons) { } public int Drive(int miles, int speed) { return 0; } } |
Advanced:
Static method |
A static method does a specific instance of the class, call time, you need to specify the class name calling |
Non-static method |
|
Method overloading |
The method of the same name, but different data types of the parameters, the number, order |
variable parameter |
We can accept a variable parameter in a one-dimensional array of columns to method parameters params properties |
Examples |
|
ref passed by reference |
When you call a method, any changes made to parameters in the method are reacted in the variable. 使用ref参数 必须方法声明 和调用方都必须显示的使用 ref关键字 |
示例 |
|
out定义输出参数 |
参数通过引用来传递。ref要求变量必须在传递前初始化。而out参数不用初始化。 必须声明和调用方都显示使用 out |
示例 |
|
参考: