Static and non-static methods
The class definition in C # can contain static and non-static methods using static modifiers.
Is a static method, and vice versa.
Static Method is a special member method. It does not belong to a specific instance of the class.
It can be any member of the primary class, but the static method can only be a static member of the primary class. See this example.
Class
{
Int x;
Static int y;
Static int F (){
X = 1; // access is not allowed due to an error
Y = 2 // access allowed properly
}
In this class definition, the static method F () can enumerate the static member s in the class but cannot access the non-static
Member x. This is because x, as a non-static member, occupies a storage or
A copy while the static method is shared by the class. It cannot determine which class of the current x instance belongs.
It does not know which address in the memory should be used to read the current x value, while y is not a static member of all classes.
In this example, a copy static method is used.
So is the static method unable to identify the instance of the class? in C #, We can flexibly use
Method of passing parameters chapter 10 we mentioned an example of a windows window program.
Example to make some changes
Program list 11-6
Using System;
Class Window
{
Public string m_caption; // window title
Public bool IsActive; // whether the window is activated
Public handle m_handle; // window handle
Public static int m_total; // Number of opened windows
Public handle window (){
M_total ++; // Add 1 to the total number of Windows
// Create some Execution Code in the window
Return m_handle; // the return value of the window as the handle
}
~ Window (){
M_total --; // The total number of windows minus 1
// Undo some Execution Code in the window
}
Public static string getwindowcaption (window W)
{
Return W. m_caption;
}
// Other window members
}
Analyze the code in the above example. Each window has a window title m_caption window handle.
M_handle window whether to activate isactive three non-static data member window handles are windows operations
A Data Structure for saving window-related information in the system. In this example, the use of the handle is simplified.
Total number of opened windows in the system m_total is used as a static member. Each window calls the constructor to create
At this time, the m_total value is added to the window to close or the value of m_total In The Destructor is used when other behaviors are revoked.
Minus 1
Pay attention to the static method getwindowcaption (window W) of the window class. Here it uses the parameter W
Pass the object to the method for execution so that it can specify the called object through the instance of a specific class.
Users can access members in a specific instance, whether static or non-static.