我读过很多关于静态字段的文章
静态方法无法访问实例字段
字段,因为实例字段仅存在于该类型的实例上。
但我们可以在静态类中创建和访问实例字段。
请找到下面的代码,
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
方法是其中的一部分,因为不会在此类的实例上调用静态方法。如果你create该类的实例,您可以像平常一样访问它的实例字段。
Your b
不是实例字段,它是普通的局部变量。
您引用的句子只是意味着您无法执行您在注释掉的行中尝试的操作:您无法访问a
没有实例。非静态方法的使用this
作为默认实例,因此您可以访问a
通过简单地写a = 17;
这相当于this.a = 17;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)