简体   繁体   中英

How to access an object in c sharp from outside my method?

I'm completely new to C#, WPF and OOP, and am facing a problem with objects.

I'm creating a small RPG and have a Player class that has a constructor automatically assigning default values to the instanciated object.

So with WPF/XAML, I created a button that is linked to a function; when I Press the button, this function will be executed:

private void NewGameClick(object sender, RoutedEventArgs e)
{
    Player hero = new Player("Tristan");

    MessageBox.Show("The character " + hero.Name + " has been created.");
}

The message box indeed shows the name of the character, but I can't use the "hero" object created by the function in the rest of my code. Is it because the object is deleted at the end of the function? Is there any way to keep that object and use it outside of that function?

Thanks!

The hero object only exists inside the NewGameClick method and will go out of scope after the method has finished executing.

You can declare your object outside of the method and it will be in the scope of that class. For instance.

public class Game 
{
    Player hero = new Player("Tristan");

    private void NewGameClick(object sender, RoutedEventArgs e)
    {       
        MessageBox.Show("The character " + hero.Name + " has been created.");
    }
}

You then have a private Player object inside the Game class to work with.

When you declare a variable inside a function you can use this variable only inside the function's scope. You have to use a member variable of your class, or to return this player.

在你的方法之外宣布你的方法之外的玩家。

If you want to use the hero object outside of this method then you should declare it as global variable outside this method.

Or better even use property to access, set and get the hero object.

I would recommend some further reading on this here: http://www.dotnetperls.com/global-variable

variables declared inside a function have a lifetime of the function itself (technically, could be shorter than function itself, due to garbage collector being too smart). What you want is to scope the variable, according to your needs. Which means, it could be scoped to a class instance as a field (ie the fields lifetime is not associated to the lifetime of the class instance), or you could scope your variable to be static (ie it lives for pretty much entire lifetime of the app, unless you clear or replace the static variable)

Make the hero variable a field of your class. You can also wrap that field into a Property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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