how to write a C# function to add arg of this class?
how to write a C# function to add arg of this class?
very basic question I think.
public class person { public string name; public int status; public int ability; public person() { } public person(string name, int status, int ability) { this.name = name; this.status = status; this.ability = ability; } public static int praise() { return ++status; } }
I want write a class with C#, it has a function to add every new class their 'status'. but there is a error because 'status' is not static . how can i solve this problem? thank you very much.
Answer by ken2k for how to write a C# function to add arg of this class?
How about making your field static?
public static int status;
Also do note that you should use properties instead of public fields...
Another thing is, you set the status
field in the constructor of your class. So it's very confusing about the role of the status
field. Do you actually want to share it between multiple instances or not?
If the status
field is not common for all of your instances, then your praise
method could take a collection of person
as parameter, and increment their status
one by one.
Maybe you should clarify your question.
Answer by dtb for how to write a C# function to add arg of this class?
Remove the static
modifier from the method declaration:
public int praise() { return ++status; }
Answer by Bryan Crosby for how to write a C# function to add arg of this class?
You can't reference a non-static field in a static context. You could make it static but that is up to your design.
Answer by Hans Z for how to write a C# function to add arg of this class?
It looks like you're trying to make praise()
increment the status of the specific person, which means it shouldn't be a static method.
public int praise() { return ++status; }
to call it you do
Person bob("bob", 0, 0); bob.praise();
Answer by Michael Bowersox for how to write a C# function to add arg of this class?
The problem is that you are trying to increment a member variable in a static method. I'm going to assume that you don't want the praise() method to be static. If that is the case, you can just change the praise() method to:
public int praise() { return ++status; }
Answer by Jeremy Holovacs for how to write a C# function to add arg of this class?
You probably want
public int praise(){ return ++status; }
Answer by Massimiliano Peluso for how to write a C# function to add arg of this class?
it depends what you are trying to acheive.
if you make status
static all the instances of your class will share the same status variable:
public static int status;
if you don't make it static each instance of your class will have its own status
variable
public int praise() { return ++status; }
Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72
0 comments:
Post a Comment