C# 静态方法可以';无法访问实例字段?

C# 静态方法可以';无法访问实例字段?,c#,.net,oop,C#,.net,Oop,我读过很多关于静态字段的文章 静态方法无法访问实例中的字段 字段,因为实例字段仅存在于类型的实例上 但是我们可以在静态类中创建和访问实例字段 请查找下面的代码 class Program { static void Main(string[] args) { } } class clsA { int a = 1; // Static methods have no way of accessing fields that are

我读过很多关于静态字段的文章

静态方法无法访问实例中的字段 字段,因为实例字段仅存在于类型的实例上

但是我们可以在静态类中创建和访问实例字段

请查找下面的代码

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;
    }
}
“我们可以访问静态方法中的非静态字段”是真的吗

另一个问题是,如果我们将class
clsA
声明为静态类,即使在那时,如果我们在静态方法中声明实例字段,我们也不会得到任何编译错误


哪里出错了?

您无法访问
静态方法所属类的实例字段,因为该类的实例上没有调用静态方法。如果创建该类的实例,则可以正常访问其实例字段

您的
b
不是一个实例字段,它是一个普通的局部变量


你引用的这句话只是意味着你不能做你在注释行中尝试过的事情:没有实例,你无法访问
a
。非静态方法使用
this
作为默认实例,因此您可以通过简单地编写
a=17来访问
a
这相当于
这个。a=17

我同意。另外,如果您将类clsA声明为静态,则不能使用new关键字对其进行实例化,这样行将明显失败。感谢nvoidgt,所以您的意思是实例字段是使用新变量创建的字段(如果我错了,请更正我)。所以,最后我们可以说,如果您必须访问非静态类的静态方法中任何特定类的实例字段,我们必须创建该类的实例吗?不,实例字段是在类中声明的变量,而不是在方法中声明的变量。互联网确实不是一个很好的媒介来解释这一点,你可能想要一本好的面向对象的书,并阅读第一章。你当地的图书馆会有一些。