【问题标题】:C# "An object reference is required for the non-static field," Class issue with Static Member FunctionC#“非静态字段需要对象引用”,静态成员函数的类问题
【发布时间】:2011-12-21 11:56:59
【问题描述】:

我正在为学校做一个项目(在 CIS 中攻读我的学士学位),我遇到了这个问题与类函数。

 public static int GetNumberCreated()
    {
        // return the total number of airplanes created using the class as the blueprint

        return numberCreated;  // returns the number of airplanes created
    }//end of public int GetNumberCreated()

在这个小型 C# 程序中,程序会返回您迄今为止制造了多少架飞机的值。 我在开头声明了 numberCreated:

private int numberCreated;

我收到经典错误“非静态字段、方法或属性需要对象引用”我已经进行了大量研究,试图弄清楚发生了什么,但我想出了没有什么。

我确实在类的底部设置了一个属性,以便表单能够访问该变量:

public int NumberCreated { get; set; }

我还尝试将属性更改为:

public int NumberCreated { get { return numberCreated; } set { numberCreated = value; } }

没有运气。 >.>'

我做错了什么?

【问题讨论】:

    标签: c# visual-studio-2008


    【解决方案1】:

    您需要将您创建的 int 号码声明为静态。

    eg public static int NumberCreated {get;set;}
    

    您可以从非静态方法访问静态成员,但不能从静态方法访问非静态成员。例如,不能从静态方法访问实例变量。

    【讨论】:

    • 谢谢 ^_^' 我不敢相信这就是我所缺少的。谢谢你。
    【解决方案2】:

    这很简单——你需要在你的方法签名之前添加“静态”关键字,就像这样:

    public static int NumberCreated { get; set; }
    

    然后你可以像这样递增/递减:

    AirplaneFactory.NumberCreated++ / AirplaneFactory.NumberCreated--
    

    【讨论】:

      【解决方案3】:

      GetNumberCreated 是一个静态方法。 numberCreated 是使用此类的对象创建的变量。所以,静态方法不知道去哪里找,因为没有这样的变量。

      您需要private static int

      【讨论】:

        【解决方案4】:

        简而言之,即使“numberCreated”尚未出现,也可以调用您的静态方法。编译器告诉您,您试图在没有任何事先保证婴儿已经出生的情况下归还婴儿。

        将 numberCreated 更改为静态属性,它会编译。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-10-22
          • 2023-03-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多