目录
先看一个静态字段的示例:
namespace Ch05Ex03
{
class Persion
{
int Mem1;
static int Mem2; //私有静态成员
static Persion()
{
Mem2 = 900;
//Mem1 = 200; //不可以在静态构造函数中初始化 非静态字段
WriteLine("静态构造函数被调用!\n");
}
public Persion(int aa,int bb)
{
Mem1 = aa;
Mem2 = bb; //利用构造函数设置私有静态成员
WriteLine("\n实例构造函数被调用!\n");
}
public void SetVars(int v1,int v2)
{
Mem1 = v1;
Mem2 = v2;
}
public void Display(string str)
{
WriteLine($"{str}: Mem1的值:{Mem1}, Mem2的值:{Mem2}");
}
}
class Program
{
static void Main(string[] args)
{
Persion d1 = new Persion(2, 8); //利用公有构造函数设置静态字段和普通字段的值
d1.Display("d1");
Persion d2 = new Persion(5, 77);
d2.Display("d2");
WriteLine();
d1.SetVars(7, 22); //利用公有成员函数设置静态字段和普通字段的值
d1.Display("d1");
d2.SetVars(99, 100);
d2.Display("d2");
d1.Display("d1"); //这里再次输出d1的值,输出就是 7,100,因为它被d2 改变了
// 注意下面的代码:
Persion d3 = new Persion(141, 55), d4 = new Persion(454, 666);
/*该代码输出:
* d3: Mem