C# "An object reference is required for the non-static field,"静态成员函数的类问题

标签 c# visual-studio-2008

我正在为学校做一个项目(在 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; } }

运气不好。 >.>'

我做错了什么?

最佳答案

您需要将创建的数字声明为静态。

eg public static int NumberCreated {get;set;}

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

关于C# "An object reference is required for the non-static field,"静态成员函数的类问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4748725/

相关文章:

c# - 将Web应用程序部署到生产中的最佳方法

c# - 迭代 T4 脚手架中的 [ComplexType] 属性?

visual-studio - 如何确定 Visual Studio 正在运行的服务包?

c++ - Thrift TNonblockingServer.cpp未声明的标识符-Windows

visual-studio - Visual Studio 2010 中的重启图标在哪里?

javascript - 将元素[数据]发布到服务器端的最佳方式

c# - 在 C#/Linq 中搜索子类型的集合

c# - WCF 发送大文件

c++ - 运算符 "delete[]": how to detect? 误用 "delete"时的行为?

visual-studio-2012 - 无法在 VS 2008 中加载 VS 2012 工作区