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

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

问题描述

我已经阅读了很多有关静态字段的文章,**静态方法无法访问作为实例字段的字段,因为实例字段仅存在于该类型的实例上." **

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 acces instance varible 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;等效于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天全站免登陆