简体   繁体   中英

C# how to create an instance of a class in one function and then use that same instance in another function

This is probably a really short answer but I just don't know the syntax for it and cant find examples of it anywhere online that involve multiple instances of classes that depend on each other.

I have this but its not working because the instance of game cannot be found because it is in another function.

All of the resources I can find are on referencing strings and objects outside/between methods but this don't even know what to do because I have tried all of those ways that they said to do with objects and variables but I just cant get it going. Because when i do it those ways as shown buy creating it before hand it always clears game to null just before it enters the second function.

public void Go()
    {
        MockFiler Mock = new MockFiler("###\n# #\n#@#\n###");
        Game game = new Game(Mock);
        game.Load("h:\theFileNameDoesNotMatterAsItReturnsAString"); // All gets created fine and used fine

        string Level = game.Level;
        View.ShowGame(Level);  // Some winforms code in here
    }


    // As soon as trigger is setoff in the winforms code it calls this function
    // as soon as the attention point comes back in this class to here the game is == null
    public void PassMove(Direction Direction) 
    {
        game.Move(Direction);  // so the instance of game becomes null and i cant call this function inside it
        string Level = game.Level;
        View.ShowGame(Level);
    }

I have tried all of those things like calling Game outside of the first method and then setting it inside that first method but it always clears it. I think it is to do with the MockFiler not setting it properly or note being accessible or something little and silly.

You should create the instance globally for both Game and MockFiler , It will be outside of both functions,

 //Creating instance and passing 
 MockFiler Mock = new MockFiler("###\n# #\n#@#\n###"); 
 //Creating instance  for Game
 Game game = new Game(Mock);
 //Now these can be accessed anywhere within the methods 
 public void Go()
  {         
    game.Load("h:\theFileNameDoesNotMatterAsItReturnsAString");
    string Level = game.Level;
    View.ShowGame(Level); 
}    
public void PassMove(Direction Direction) 
{
    game.Move(Direction);  
    string Level = game.Level;
    View.ShowGame(Level);
}

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