通常我们知道,为了访问静态变量,我们不需要创建类的实例。我们可以直接做like classname.staticvariable
。为了访问类中的静态变量,我们应该有一个静态方法。
现在我对以下代码片段有疑问
public class xyz
{
private static int a;
public xyz()
{
a++;
}
}
上面的代码片段会起作用吗?如果是,为什么,如果不是,为什么?
谢谢普拉班詹
是的,它会。int 的默认值为 0。每次调用构造函数时,都会增加静态变量。
有用。
想象一下,您想知道已创建了多少个类的实例。所以在这种情况下你可以使用
xyz.a
此外,要监控活动实例的数量,您可以创建一个析构函数并使用a--
.
To quote from the C# documentation on static variables:
Static members are initialized before the static member is accessed for the first time and before the static constructor, if there is one, is called.
For example run the following sample program:
using System;
namespace ScrapCSConsole
{
class ScrapCSConsole
{
public static void Main()
{
Console.WriteLine("Create StaticDemo A");
StaticDemo a = new StaticDemo();
Console.WriteLine("Create StaticDemo B");
StaticDemo b = new StaticDemo();
Console.WriteLine("Done");
}
}
class StaticDemo
{
private static int staticDemo1;
private static int staticDemo2 = 0;
private static int staticDemo3 = default(int);
private static int staticDemo4;
private static int classNumber;
/// <summary>
/// Static Constructor
/// </summary>
static StaticDemo()
{
Console.WriteLine("Static Constructor");
Console.WriteLine("staticDemo1 {0}", staticDemo1);
staticDemo4 = (new DateTime(1999, 12, 31)).DayOfYear;
}
/// <summary>
/// Instance Constructor
/// </summary>
public StaticDemo()
{
classNumber++;
Console.WriteLine("classNumber {0}", classNumber);
Console.WriteLine("staticDemo2 {0}", staticDemo2);
Console.WriteLine("staticDemo3 {0}", staticDemo3);
Console.WriteLine("staticDemo4 {0}", staticDemo4);
}
}
}
And you get the following output:
Create StaticDemo A
Static Constructor
staticDemo1 0
classNumber 1
staticDemo2 0
staticDemo3 0
staticDemo4 365
Create StaticDemo B
classNumber 2
staticDemo2 0
staticDemo3 0
staticDemo4 365
Done
There are some interesting things to note here:
Finally as a sub note you need to be careful if you are creating the objects on multiple threads. This is because classNumber++ is not an atomic operation. It counts as two seperate operations one read and one write. As such two seperate threads can both read the variable before either one of them writes out the incremented value. To avoid this situation use this line instead:
System.Threading.Interlocked.Increment(ref classNumber);
从实例方法访问静态成员是非常好的。
静态变量a
有一个默认值,0
每次创建类的实例时,您的代码都会递增它。
上面的代码片段将完美地工作。编写此类代码是为了计算类中存在的活动实例的数量。
public class xyz
{
private static int a;
public xyz()
{
a++;
}
public static int A
{
get { return a;}
}
}
将活动实例的数量打印为:
Console.WriteLine(obj.A);
以下假设不正确;
为了访问类中的静态变量,我们应该有一个静态方法。
您提供的代码有效,因为您不需要静态方法。
试试下面的,你会发现它也有效;
public class xyz
{
private static int a;
public void A()
{
a++;
}
}
是的,它会起作用。您可以在实例成员中引用静态成员,但不能在静态成员中引用实例成员,因为它们需要实例才能工作,而静态不需要。
It doesn't work if you want access to static var, you must decalar it public and Constructor method doesn't run, because constructors runs when you use initialize a class and create an object.