2013-01-02 133 views
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; 
} 

} 

回答

5

靜態字段通常用於編譯時間常數,因此是很有意義,使對它們的訪問無痛。因此它們可以從它們的封閉類型的實例中訪問。

此外,靜態成員由於顯而易見的原因(它不與實例關聯,但僅與類型關聯)無法引用實例成員。但是反過來也不是問題,因爲實例通常知道它自己的類型,因此也可以查找靜態成員。

相關問題