The class definition of C # can contain two methods: Static and Non-static. A static modifier is used, whereas the other is non-static.
A static method is a special member method that does not belong to a specific instance of a class. Non-static methods can access any member of a class, while static can only access static members in a class. Look at this example:
Class A
{
int x;
static int y;
static int F () {
x=1;//error, Access y=2 not allowed
;//correct, allow access
}
In this class definition, static method F () can access static member Y in the class, but cannot access non-static member X. This is because, X as a non-static member, each instance of the class occupies a storage (or a copy), and the static method is shared by the class, and it cannot tell what class the current x belongs to, so it does not know which address in memory to read the value of the current x. And y is a static member, all instances of the class have a common copy, and static method F uses it without any problems.
So is it possible for static methods to recognize instances of classes? In C #, we can flexibly adopt the method of passing parameters. In the tenth chapter we mention a Windows window example where we can make some changes to this example.
Program Listing 11-6:
Using System;
Class Window
{public
string m_caption; The title of the window is public
bool isactive;//Determines whether the public handle m_handle is activated;//
The handle of the window is public
static int m_total; The number of Windows currently open
handle window () {
m_total++;//total number of Windows plus 1//
... Create some execution code for the window
return m_handle//window returns value as handle
}
~window () {
m_total--;//total number of Windows minus 1
//... Undo some execution code for the window
} public
static string getwindowcaption (window W)
{return
w.m_caption;
}
//...... Other members of the window
}
Analyze the code in the example above. Each window has a window title m_caption, Window handle m_handle, window activation isactive three non-static data members (window handles are a data structure that holds window-related information in the Windows operating system, and we simplify the use of handles in this example). The total number of Windows open in the system m_total as a static member. Each window invokes the constructor creation, at which point the M_total value is added to 1. When the window closes or is undone by another behavior, the value of the destructor m_total is reduced by 1.
We want to note the static method Getwindowcaption (window W) of the Windows class. Here it passes the object to the method execution through the argument W, so that it can indicate the invoked object through an instance of the concrete class, and then it can access the members in the concrete instance, either static or non-static members.