How do I call a Method in C#?
I'm trying to learn how methods work in C# (Also using the XNA Framework).
This is the method I made.
public void Exit()
{
if (Keyboard.GetState().IsKeyDown(Keys.Escape))
{
this.Exit();
}
I'm under the impression that it's in the proper format. But I don't know how to actually c开发者_如何转开发all it. Or perhaps I'm doing it wrong?
You have to start somewhere I guess... You seem to have writen a recursive inifinte loop without knowing it!
public void Exit()
{
if (Keyboard.GetState().IsKeyDown(Keys.Escape))
{
this.Exit(); // this is calling your own Exit() method we we are in at the moment!
}
}
I think what you want is:
public void Exit()
{
if (Keyboard.GetState().IsKeyDown(Keys.Escape))
{
Environment.Exit();
}
}
Methods are members of a class (or struct) and are called through an instance of the class. For example:
public class Foo {
public void Bar()
{
Console.WriteLine("Running the Bar method");
}
}
You would then have code somewhere like:
Foo fooVar = new Foo();
fooVar.Bar(); // call the Bar method
Alternatively, you could define a static method which does not require an instance of the class. For example:
public class Foo {
public static void Bar()
{
Console.WriteLine("Running the static Bar method");
}
}
You would then call this in your code like this:
Foo.Bar(); // Foo is the name of class, not an object of type Foo
Also check out Charles Petzold's .Net Book Zero for a great introduction to C# and .Net.
Two things stand-out:
- You're missing a
}
at the end. this.Exit()
is a recursive call.
Methods are always declared on objects (like classes) and this
refers to the current object, so this.Exit()
will continuously call itself while the Esc is held down.
What is it that you are trying to accomplish with your code?
For this particular method you just call it like this:
Exit();
insert that as a line anywhere and it will work. Before you do that though check the this.Exit();
line, you don't want to be recursively calling yourself....
But looking at the other lines of code in the method i'm not sure that's exactly what you want to do - do you want to exit when a specific key is pressed in conjunction with the Esc
key?
I believe that Microsoft.Xna.Framework.Game
(which you are inheriting from (I think)) provides an 'Update' method which you should override.
Overriding basically replaces method of the base class with whatever you want. In this case calling a method which checks the state of the keyboard and exits when escape is pressed.
Update is called every time the game should, unsurprisingly, update itself (what's on the screen, player position, etc.)
protected override void Update(GameTime gameTime)
{
// ....
ProcessKeyboard(); // Calls into ProcessKeyboard()
//....
}
private void ProcessKeyboard () // A new method
{
if (Keyboard.GetState().IsKeyDown(Keys.Escape))
{
this.Exit(); // Provided from Microsoft.Xna.Framework.Game
}
// Handle other keys down here.
}
精彩评论