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