簡體   English   中英

C#如何在一個函數中創建一個類的實例,然后在另一個函數中使用同一個實例

[英]C# how to create an instance of a class in one function and then use that same instance in another 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);
    }

我已經嘗試了所有這些事情,比如在第一個方法之外調用 Game 然后在第一個方法中設置它,但它總是清除它。 我認為這與 MockFiler 沒有正確設置它或注意可訪問性或一些小而愚蠢的事情有關。

您應該為 Game 和 MockFiler 全局創建實例,它將在兩個函數之外,

 //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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM