静态方法无法访问实例字段
本文关键字:实例 字段 访问 静态方法 | 更新日期: 2023-09-27 18:34:13
我读过很多关于静态字段的文章
静态方法无法访问实例字段字段,因为实例字段仅存在于该类型的实例上。
但是我们可以在静态类中创建和访问实例字段。
请在下面找到代码,
class Program
{
static void Main(string[] args)
{
}
}
class clsA
{
int a = 1;
// Static methods have no way of accessing fields that are instance fields,
// as instance fields only exist on instances of the type.
public static void Method1Static()
{
// Here we can create and also access instance fields
// which we have declared inside the static method
int b = 1;
// a = 2; We get an error when we try to access instance variable outside the static method
// An object reference is required for the non-static field, method, or property
Program pgm = new Program();
// Here we can create and also access instance fields by creating the instance of the concrete class
clsA obj = new clsA();
obj.a = 1;
}
}
这是真的"我们可以访问静态方法中的非静态字段"吗?
另一个问题如果我们将类clsA
声明为静态类,即使在那时,如果我们在静态方法中声明实例字段,我们也不会收到任何编译错误?
我哪里错了?
您不能访问static
方法所属的类的实例字段,因为不会在此类的实例上调用静态方法。如果创建该类的实例,则可以正常访问其实例字段。
您的b
不是实例字段,而是普通的局部变量。
你引用的这句话只是意味着你不能做你在注释掉的行中尝试过的事情:没有实例你就无法访问a
。非静态方法使用 this
作为默认实例,因此您只需编写等效于 this.a = 17;
a = 17;
即可访问a