C#如何在另一个程序中使用程序中的字符串
我在练习一些代码 我有这个密码 班级计划C#如何在另一个程序中使用程序中的字符串,c#,string,methods,call,C#,String,Methods,Call,我在练习一些代码 我有这个密码 班级计划 { static void Main(string[] args) { Program a = new Program(); a.Alalao(); Program b = new Program(); b.Game(); } public void Alalao() { Console.WriteLine("Hello
{
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);
}
}
如何将Alalao()中的字符串n1放入游戏()中的最后一个命令Console.writeline中
提前谢谢。有多种可能的方法。一种解决方案是使用参数/返回值
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);
}
这就是结构化编程的全部内容,您可以将较大的问题划分为较小的块(方法),但仍然可以使用参数和返回值来传达这些块
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);
}
从Alalao返回n1并将其作为参数添加到游戏中。就像这样
public string Alaloa () {
// ...
string n1 = Console.ReadLine();
// ...
return n1;
}
// ...
public void Game (string inString) {
// ..
Console.WriteLine("{0}, are you ready start?", inString);
}
然后需要将Alaloa的返回值保存为变量,并将其添加到主方法中的游戏调用中,如下所示
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);
}