简体   繁体   English

C# 如何在另一个程序中使用字符串

[英]C# how to use an string from an program in another

I am practicing some code.我正在练习一些代码。

i have this code我有这个代码

class Program class 程序

{

    static void Main(string[] args)

    {

        Program a = new Program();
        a.Alalao();
        Program b = new Program();
        b.Game();
    }
    public void Alalao()
    {
        Console.WriteLine("Hello my dear. How would you like to be called?");
        string n1 = Console.ReadLine();
        // more code
    }
    public void Game()
    {
        Console.WriteLine("This is a game where you have answer questions. For each correct answer 1 get an point and for each wrong answer you lose a point.");
        Console.WriteLine("You will start with 5 points. Consider it as a courtesy");
        Console.WriteLine("{0}, are you ready start?", n1);
    }
}

How can i put the string n1 from Alalao() inside the last command Console.writeline in Game()如何将来自 Alalao() 的字符串 n1 放入 Game() 中的最后一个命令 Console.writeline

Thank you in advance.先感谢您。

There are multiple possible ways.有多种可能的方式。 One solution is to use arguments/return values.一种解决方案是使用参数/返回值。

This is what structural programming is all about, you divide a larger problem into smaller chunks (methods) but still, you communicate these chunks using parameters and return values.这就是结构化编程的全部内容,您将较大的问题分成较小的块(方法),但您仍然使用参数和返回值来传达这些块。

static void Main(string[] args)
{

    Program a = new Program();
    var name = a.Alalao();
    Program b = new Program();
    b.Game(name);
}

public string Alalao()
{
    Console.WriteLine("Hello my dear. How would you like to be called?");
    string n1 = Console.ReadLine();
    // more code

    return n1;
}
public void Game(string n1)
{
    Console.WriteLine("This is a game where you have answer questions. For each correct answer 1 get an point and for each wrong answer you lose a point.");
    Console.WriteLine("You will start with 5 points. Consider it as a courtesy");
    Console.WriteLine("{0}, are you ready start?", n1);
}

Return n1 from Alalao and add it as a parameter to Game.从 Alalao 返回n1并将其作为参数添加到 Game。 Like so...像这样...

public string Alaloa () {
  // ...
  string n1 = Console.ReadLine();
  // ...
  return n1;
}

// ...

public void Game (string inString) {
  // ..
  Console.WriteLine("{0}, are you ready start?", inString);
}

You will need to then save the return value from Alaloa as a variable and add it to the invocation of Game in the main method, like so...然后,您需要将 Alaloa 的返回值保存为变量,并将其添加到 main 方法中的 Game 调用中,就像这样......

static void Main (string[] args) {
  Program a = new Program();
  string myString = a.Alaloa(); // Saving the string to a variable
  
  Program b = new Program();
  b.Game(myString);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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