我知道静态方法不能访问作为实例字段的字段,它让我困惑的是:为什么非静态方法可以访问静态字段currentID?在下面的代码中,currentID是静态字段,getNextID是静态函数。令人惊讶的是,它无错误地传递编译。
public class WorkItem
{
// Static field currentID stores the job ID of the last WorkItem that
// has been created.
private static int currentID;
//Properties.
protected int ID { get; set; }
protected string Title { get; set; }
protected string Description { get; set; }
protected TimeSpan jobLength { get; set; }
public WorkItem()
{
ID = 0;
Title = "Default title";
Description = "Default description.";
jobLength = new TimeSpan();
}
// Instance constructor that has three parameters.
public WorkItem(string title, string desc, TimeSpan joblen)
{
this.ID = GetNextID();
this.Title = title;
this.Description = desc;
this.jobLength = joblen;
}
// Static constructor to initialize the static member, currentID. This
// constructor is called one time, automatically, before any instance
// of WorkItem or ChangeRequest is created, or currentID is referenced.
static WorkItem()
{
currentID = 0;
}
protected int GetNextID()
{
// currentID is a static field. It is incremented each time a new
// instance of WorkItem is created.
return ++currentID;
}
}
答案 0 :(得分:5)
静态字段通常用于编译时常量,因此无意义地访问它们是有意义的。因此,可以从它们的封闭类型的实例访问它们。
此外,静态成员由于显而易见的原因无法引用实例成员(它与实例无关,只与类型相关联)。反之亦然没有问题,因为实例通常知道它自己的类型,因此也可以查找静态成员。