当心静态字段
今天写代码的时候写错了,代码如下:
class TestStatic
{
static int a;
public int A
{
get
{
return a;
}
set
{
a = value;
}
}
}
class Program
{
static void Main(string[] args)
{
TestStatic testStatic1 = new TestStatic();
testStatic1.A = 1;
TestStatic testStatic2 = new TestStatic();
testStatic2.A = 2;
Console.WriteLine("testStatic1.A={0}", testStatic1.A);
Console.WriteLine("testStatic2.A={0}", testStatic2.A);
}
}
{
static int a;
public int A
{
get
{
return a;
}
set
{
a = value;
}
}
}
class Program
{
static void Main(string[] args)
{
TestStatic testStatic1 = new TestStatic();
testStatic1.A = 1;
TestStatic testStatic2 = new TestStatic();
testStatic2.A = 2;
Console.WriteLine("testStatic1.A={0}", testStatic1.A);
Console.WriteLine("testStatic2.A={0}", testStatic2.A);
}
}
定义int a的时候应该写private,不小心写成了static,运行结果让我很茫然:
testStatic1.A=2
testStatic2.A=2
仔细检查下,哦,原来是关键字写错了。但是结果为什么是这样呢?肯定是static引起的,就查static吧。翻了一下MSDN,还在网上google了一下,最后在《C#编程指南》(《C#编程指南》所在目录是..\Visual Studio 2005\VC#\Specifications\2052)中找打了答案,他这样介绍静态字段:一个静态字段只标识一个存储位置。对一个类无论创建了多少个实例,它的静态字段永远都只有一个副本。
写段代码测试一下:
class TestStatic
{
private static int a;
public int A
{
get
{
return a;
}
set
{
a = value;
}
}
public static void Changea(int c)
{
a=c;
}
}
class Program
{
static void Main(string[] args)
{
//两个对象
TestStatic testStatic1 = new TestStatic();
TestStatic testStatic2 = new TestStatic();
//默认值
Console.WriteLine("testStatic1.A={0}", testStatic1.A);
Console.WriteLine("testStatic2.A={0}", testStatic2.A);
//通过对象1赋值
testStatic1.A = 1;
Console.WriteLine("testStatic1.A={0}", testStatic1.A);
Console.WriteLine("testStatic2.A={0}", testStatic2.A);
//通过对象2赋值
testStatic2.A = 2;
Console.WriteLine("testStatic1.A={0}", testStatic1.A);
Console.WriteLine("testStatic2.A={0}", testStatic2.A);
//通过静态方法赋值
TestStatic.Changea(4);
Console.WriteLine("testStatic1.A={0}", testStatic1.A);
Console.WriteLine("testStatic2.A={0}", testStatic2.A);
Console.ReadKey();
}
}
{
private static int a;
public int A
{
get
{
return a;
}
set
{
a = value;
}
}
public static void Changea(int c)
{
a=c;
}
}
class Program
{
static void Main(string[] args)
{
//两个对象
TestStatic testStatic1 = new TestStatic();
TestStatic testStatic2 = new TestStatic();
//默认值
Console.WriteLine("testStatic1.A={0}", testStatic1.A);
Console.WriteLine("testStatic2.A={0}", testStatic2.A);
//通过对象1赋值
testStatic1.A = 1;
Console.WriteLine("testStatic1.A={0}", testStatic1.A);
Console.WriteLine("testStatic2.A={0}", testStatic2.A);
//通过对象2赋值
testStatic2.A = 2;
Console.WriteLine("testStatic1.A={0}", testStatic1.A);
Console.WriteLine("testStatic2.A={0}", testStatic2.A);
//通过静态方法赋值
TestStatic.Changea(4);
Console.WriteLine("testStatic1.A={0}", testStatic1.A);
Console.WriteLine("testStatic2.A={0}", testStatic2.A);
Console.ReadKey();
}
}
运行结果:
testStatic1.A=0
testStatic2.A=0
testStatic1.A=1
testStatic2.A=1
testStatic1.A=2
testStatic2.A=2
testStatic1.A=4
testStatic2.A=4
可见不关用什么方法改变a的值两个对象的a(其实是同一个a)都会同时改变。
结论:不要改变实例类中的静态字段,不要给私有字段定义属性。
如有错误或不当之处请拍砖。

浙公网安备 33010602011771号