gpt4 book ai didi

c# - 为什么非静态方法可以访问静态字段?

转载 作者:太空宇宙 更新时间:2023-11-03 20:20:08 25 4
gpt4 key购买 nike

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

}

最佳答案

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

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

关于c# - 为什么非静态方法可以访问静态字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14118315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com