【发布时间】:2015-02-12 14:55:16
【问题描述】:
我读过很多关于静态字段的文章
静态方法无法访问实例字段 字段,因为实例字段仅存在于该类型的实例上。
但我们可以在静态类中创建和访问实例字段。
请在下面找到代码,
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 类声明为静态类,即使我们在静态方法中声明实例字段,也不会出现任何编译错误?
我哪里错了?
【问题讨论】: