2017-02-17 34 views
0

我試圖在主類中設置一個字符串,並將其發送給我的名稱類,然後稍後在主類的另一個方法中使用它。 這就是我所擁有的。如何在一個類中創建一個字符串並在另一個類中使用它

我對編碼相當陌生,今年剛上課。任何幫助。

我只是想做一個簡單的冒險遊戲。

提前致謝!

class Player 
{ 
    public string playerName { get; set; } 
} 

class MainClass 
{ 
    public static void nameSelection() 
    { 
     Player player = new Player(); 


     Console.Clear(); 
     Console.WriteLine ("Let's start off simple adventurer, what is your name?"); 
     player.playerName = Console.ReadLine(); 

     Console.Clear(); 
     Console.WriteLine ("Are you sure {0} is your name? Type 1 for yes and 2 for no", player.playerName); 
     string confirm = Console.ReadLine(); 

     if (confirm == "1") { 
      Console.Clear(); 
      Console.WriteLine ("Okay {0}, here we go!", player.playerName); 
      Console.ReadLine(); 

     } 
     else if (confirm == "2") { 
      Console.Clear(); 
      nameSelection(); 
     } 
     else 
     { 
      Console.Clear(); 
      nameSelection(); 
     } 

    } 

public static void classselsction() 
{ 

     Console.ReadLine(); 
     Console.WriteLine ("As you get to the end of the hallway you see a shadow."); 
     Console.ReadLine(); 
     Console.WriteLine("Hello {0}, I see you have managed to escape from your cell. " + 
      "You have proven yourself quite worthey.", player.playerName); 
     Console.ReadLine(); 
    } 
} 
+0

嗨,歡迎來到SO。您是否收到錯誤,您得到的結果與您的期望不符? – miltonb

回答

2

作爲David的建議的替代方案,您可以考慮將您的Player類實例作爲MainClass的成員。類似這樣的:

class MainClass 
{   
    static Player player = new Player(); 
    public static void nameSelection() 
    { 
     // Set player.playerName here 
     ... 
    } 
    public static void classselsction() 
    { 
     // Use player.playerName here. 
     ... 
    } 
} 

我同意他的「無關」評論。遞歸可以是一個很好的工具,但這裏不需要。 KISS

+0

我試過了,它似乎沒有解決任何問題,實際上它打破了一切。 – Josh

+0

我很抱歉,當我第一次嘗試這個時,我必須輸入錯誤的東西,因爲它現在正在工作,非常感謝! – Josh

2

因此該方法nameSelection()內部創建一個變量,並希望該變量提供給方法時,它調用它classselsction()?只要將其添加爲一個方法參數:

public static void classselsction(Player player) 
{ 
    // the code you already have 
} 

然後當你調用該方法,你會爲它提供您所創建的對象:

classselsction(player); 

(請注意,您目前沒有停靠方法。所有但從描述這聽起來像你打算這樣做)


無關:你可能要重新考慮你在nameSelection()正在進行的遞歸結構。當你想重新啓動基於用戶輸入的邏輯時,考慮一個循環而不是遞歸。你所做的並不是真正的遞歸的事情,你只是重新要求用戶輸入,直到滿足條件,這更多的是循環。這種遞歸會引起與您的player變量的狀態不必要的混淆,否則,這是任何給定的方法調用的局部變量。

根據方法的名稱,你可能不希望他們互相呼叫。我想應該有一些更高層次的方法,在需要輸入時依次調用它們中的每一個。雖然關於你正在構建的整體結構的討論可能會很快超出這個問題的範圍。

基本上,作爲一個建議的話...永遠不要試圖讓你的代碼聰明。簡單的事情比複雜的事情要好。

+0

基本上我做了你所說的添加方法參數,classselection(player);但它說在當前上下文中不存在「播放器」的名稱 – Josh

+0

所以我弄明白了,只是在類MainClass中使其成爲靜態的,我可以在我想要的方法中調用它,謝謝你嘗試幫助; D – Josh

+0

@JoshuaBohning:繼續回答這個問題的後半部分......只是隨意地將所有東西靜態化以便編譯將會導致設計中的各種問題。我建議你考慮一下如何爲對象建模以及它們應該如何交互,不要隨意鍵入關鍵字,直到它有效。 – David

相關問題