为什么,当我运行此代码时,第二种方法的问题会重复吗?
using System;
namespace mdisafmidf
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hello world!");
CallMethod0();
Console.WriteLine(CallMethod0());
Console.ReadKey();
}
public static string CallMethod0()
{
string x;
Console.WriteLine("Do you agree this is a good day?");
Console.WriteLine("a)Yes b)No");
x = Console.ReadLine();
if (x == "Yes")
{
return ("Of course this is a good day");
}
else
{
return ("Oh, try and stay more positive!");
}
}
}
}
答案 0 :(得分:7)
你正在调用该方法两次,所以它正在运行两次。
CallMethod0();
Console.WriteLine(CallMethod0());
答案 1 :(得分:2)
运行CallMethod0
时,它会返回一个字符串。您需要将结果存储到字符串变量,然后Console.Write变量。由于你有两次方法调用,它运行了两次。
换句话说,将其更改为:
public static void Main(string[] args)
{
Console.WriteLine("Hello world!");
string result = CallMethod0(); // store the result like this
Console.WriteLine(result); // print the result - don't call the method again
Console.ReadKey();
}
答案 2 :(得分:0)
只需将您的代码修改为:
var message = CallMethod0();
Console.WriteLine(message);
答案 3 :(得分:0)
您正在使用CallMethod0()
两次
上方有CallMethod0();
和Console.WriteLine(callMethod0());
如果您删除CallMethod0();
,则可以正常使用。