2017-02-17 79 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

相关问题