静态方法无法访问实例字段? [英] Static methods can't access instance fields?

查看:84
本文介绍了静态方法无法访问实例字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了很多关于静态字段的文章

I have read many article regarding the static fields that

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

Static methods have no way of accessing fields that are instance fields, as instance fields only exist on instances of the type.

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

But we can create and access the instance fields inside the static class.

请找到下面的代码,

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;
    }
}

我们可以访问静态方法中的非静态字段"是真的吗??

Is that true "We can access the non static fields inside static method" ?

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

Another question If we declare class clsA as static class even at that time we are not getting any compilation error if we declare instance fields inside the static method?

我哪里出错了?

推荐答案

您无法访问 static 方法所属的类的实例字段,因为未在实例上调用静态方法这个班的.如果您创建该类的一个实例,您可以正常访问它的实例字段.

You cannot access instance fields of the class that the static method is part of, because a static method is not called on an instance of this class. If you create an instance of that class, you can access it's instance fields as normal.

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

Your b is not an instance field, it's a normal local variable.

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

The sentence you quoted just means that you cannot do what you tried in the line you commented out: you cannot access a without an instance. Non-static methods use this as the default instance, so you could access a by simply writing a = 17; which is equivalent to this.a = 17;

这篇关于静态方法无法访问实例字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆