You do not know Static, do not know Static
Static field, Static method, Static code block
Yi Introduction
In some scenarios, multiple instances of a class are required to share a member variable. Sometimes, you want to define methods that are not associated with a specific object and can be called without a new one.
Example: WriteLine of the Console class, Show of MessageBox. In this case, static data is used.
Static methods and static members are class methods and class members. They do not belong to any object. Therefore, you can use the direct type. Static Method () instead of the new method.
II.Features
1. static variables can be called directly by class name without the need for new. Static variables are shared memory space, and non-static variables are isolated from objects.
2. this keyword cannot be used in the static method, because static exists independently of objects and is not unique to anyone.
3. static members can only access static members, but cannot directly access non-static members. Non-static members can access static members.
ParameterStatic code block
1. Example
class
MyTest
{
static
MyTest()
{
Console.WriteLine(
"Static code block"
);
}
public
MyTest()
{
Console.WriteLine(
"Constructor"
);
}
}
MyTest t1 =
new
MyTest();
MyTest t2 =
new
MyTest();
2. description 1. A static code block is executed once when the class is used for the first time. If the class is used, even if there is no new object (such as declaring a variable), the code is executed only once. 2. Static code block, which is executed before the constructor is executed. 3. Questions
public
class
MyJingTaiDaimaKuai
{
public
static
int
i = test1();
// Start execution
public
int
age = test2();
// Initialize the member variable before executing the constructor.
static
MyJingTaiDaimaKuai()
{
Console.WriteLine(
"Static code block"
);
// Re-Execute
}
public
MyJingTaiDaimaKuai()
{
Console.WriteLine(
"Constructor"
);
}
public
static
int
test1()
{
Console.WriteLine(
"test1"
);
return
3;
}
public
static
int
test2()
{
Console.WriteLine(
"test2"
);
return
333;
}
}
MyJingTaiDaimaKuai a1 =
new
MyJingTaiDaimaKuai();
Console.WriteLine(a1.age);
MyJingTaiDaimaKuai a2 =
new
MyJingTaiDaimaKuai();
Console.WriteLine(a2.age);
/* The above Code is described as follows * // ** 1. As long as the class is exposed, the static member variables in the class are first executed. * 2. The second is the static code block. * 3. The declaration and definition of static member variables are executed only once during the first loading. * 4. The "dynamic" member variable is executed before the constructor. * 5. "dynamic" member variables are executed every time an object is instantiated. */
Reference page: http://qingqingquege.cnblogs.com/p/5933752.html