简体   繁体   English

C#“非静态字段需要对象引用”,静态成员函数的类问题

[英]C# “An object reference is required for the non-static field,” Class issue with Static Member Function

I'm working on a project for school (going for my BA in CIS) and I've come across this issue with a class function. 我正在为一个学校项目工作(即将获得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()

It's for a program to return the value of how many airplanes you've made thus far in this small C# program. 这是一个程序,返回您迄今为止在此小型C#程序中制造了多少架飞机的值。 I declared numberCreated at the beginning: 我在一开始就声明numberCreate:

private int numberCreated;

I get the classic error "An object reference is required for the non-static field, method, or property" I've done a decent amount of research trying to figure out what is going on but i've come up with nothing. 我收到经典错误消息:“非静态字段,方法或属性需要对象引用”。我已经做了相当多的研究,试图弄清楚到底是怎么回事,但我什么也没想出来。

I did however set a property at the bottom of the class so that a form would be able to access the variable: 但是,我确实在类的底部设置了一个属性,以便表单可以访问该变量:

public int NumberCreated { get; set; }

I also attempted changing the property to this: 我还尝试将属性更改为此:

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

with no luck. 没有运气。 >.>' >。>'

What am i doing wrong? 我究竟做错了什么?

You need to declare your number created int as static. 您需要将创建的int数字声明为静态。

eg public static int NumberCreated {get;set;}

You can access a static member from a non static method, but you cant access a non static member from a static method. 您可以从非静态方法访问静态成员,但不能从静态方法访问非静态成员。 eg, instance variables are not accessable from static methods. 例如,实例变量不能从静态方法访问。

It's a simple thing - you need to add the "static" keyword before your method signature, like so: 这很简单-您需要在方法签名之前添加“ static”关键字,如下所示:

public static int NumberCreated { get; set; }

Then you can increment / decrement like so: 然后,您可以像这样递增/递减:

AirplaneFactory.NumberCreated++ / AirplaneFactory.NumberCreated--

GetNumberCreated is a static method. GetNumberCreated是一个静态方法。 The numberCreated is a variable that is created with the object of this class. numberCreated是使用此类的对象创建的变量。 So, the static method doesn't know where to look, because there is no such variable. 因此,静态方法不知道在哪里查看,因为没有这样的变量。

You need a private static int . 您需要一个private static int

In a nutshell, your static method can be called even when "numberCreated" has not been brought into existence yet. 简而言之,即使尚未创建“ numberCreated”,也可以调用您的静态方法。 The compiler is telling you that you're trying to return a baby without any prior guarantee that it's been born. 编译器告诉您,您正在试图返回婴儿而没有任何事先保证。

Change numberCreated to a static property and it'll compile. 将numberCreated更改为静态属性,它将进行编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM