1

我知道静态方法不能访问实例字段,让我困惑的是:为什么非静态方法可以访问静态字段 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;
}

}
4

1 回答 1

5

静态字段通常用于编译时常量,因此轻松访问它们是有意义的。因此,它们可以从其封闭类型的实例中访问。

此外,由于显而易见的原因,静态成员不能引用实例成员(它不与实例关联,而仅与类型关联)。但反之亦然,因为实例通常知道自己的类型,因此也可以查找静态成员。

于 2013-01-02T07:26:12.677 回答