开发者

C# "An object reference is required for the non-static field," Class issue with Static Member Function

开发者 https://www.devze.com 2023-02-06 06:47 出处:网络
I\'m working on a project for school (going for my BA in CIS) and I\'ve come across this issue with a class functio开发者_开发知识库n.

I'm working on a project for school (going for my BA in CIS) and I've come across this issue with a class functio开发者_开发知识库n.

 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. I declared numberCreated at the beginning:

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.

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:

public static int NumberCreated { get; set; }

Then you can increment / decrement like so:

AirplaneFactory.NumberCreated++ / AirplaneFactory.NumberCreated--


GetNumberCreated is a static method. The numberCreated is a variable that is created with the object of this class. So, the static method doesn't know where to look, because there is no such variable.

You need a private static int.


In a nutshell, your static method can be called even when "numberCreated" has not been brought into existence yet. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号