【问题标题】:Static methods can't access instance fields?静态方法不能访问实例字段?
【发布时间】: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 类声明为静态类,即使我们在静态方法中声明实例字段,也不会出现任何编译错误?

我哪里错了?

【问题讨论】:

    标签: c# .net oop


    【解决方案1】:

    您无法访问 static 方法所属的类的实例字段,因为不会在此类的实例上调用静态方法。如果您创建该类的实例,则可以正常访问它的实例字段。

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

    您引用的句子只是意味着您无法执行您在注释掉的行中尝试的操作:您无法在没有实例的情况下访问a。非静态方法使用this 作为默认实例,因此您可以通过简单地编写a = 17; 来访问a,相当于this.a = 17;

    【讨论】:

    • 我同意。此外,如果您将类 clsA 声明为静态,则无法使用 new 关键字对其进行实例化,因此该行显然会失败。
    • 谢谢 nvoidgt,所以您的意思是实例字段是使用新变量创建的字段(如果我错了,请纠正我)。那么,最后我们可以说,如果您必须在非静态类的静态方法中访问任何特定类的实例字段,我们必须创建该类的实例吗?
    • 不,实例字段是在类中声明的那些变量,但不在方法中。互联网确实不是解释这一点的好媒介,您可能想要一本好的 OOP 书籍并阅读第一章。您当地的图书馆会有一些。
    猜你喜欢
    • 2019-12-26
    • 1970-01-01
    • 2015-01-30
    • 2014-02-19
    • 2012-01-28
    • 2015-03-19
    • 1970-01-01
    • 2016-02-25
    • 2023-03-07
    相关资源
    最近更新 更多