C#:如何使用从不同类返回
因为我是个完全的初学者,所以我对C#还不太了解。C#:如何使用从不同类返回,c#,return,C#,Return,因为我是个完全的初学者,所以我对C#还不太了解。 我想在我的主方法中使用方法1返回的字符串。 既然Method1是公共的,我就不能使用它吗 public string Method1() { Console.Write("Vorname: "); string vorname = Convert.ToString(Console.ReadLine()); Console.Write("Nachname: "); string nachname = Convert.
我想在我的主方法中使用方法1返回的字符串。
既然
Method1
是公共的,我就不能使用它吗
public string Method1()
{
Console.Write("Vorname: ");
string vorname = Convert.ToString(Console.ReadLine());
Console.Write("Nachname: ");
string nachname = Convert.ToString(Console.ReadLine());
Console.Write("Adresse: ");
string adresse = Convert.ToString(Console.ReadLine());
string info = vorname + nachname + adresse;
return (info);
}
static void Main(string[] args)
{
string dateipfad = @"C:\Users\kaihe\Documents\persönliche_informationen.txt";
AllMethods txtfileabfrage = new AllMethods();
txtfileabfrage.Method2();
AllMethods input = new AllMethods();
Console.WriteLine(info);
File.WriteAllText(dateipfad, info);
Console.ReadKey();
}
如果将static关键字添加到Method1(),则可以从main方法调用Method1()
static void Main(string[] args)
{
String returnedValue = Method1();
}
public static string Method1()
{
Console.Write("Vorname: ");
string vorname = Convert.ToString(Console.ReadLine());
Console.Write("Nachname: ");
string nachname = Convert.ToString(Console.ReadLine());
Console.Write("Adresse: ");
string adresse = Convert.ToString(Console.ReadLine());
string info = vorname + nachname + adresse;
return (info);
}
如果将static关键字添加到Method1(),则可以从main方法调用Method1()
static void Main(string[] args)
{
String returnedValue = Method1();
}
public static string Method1()
{
Console.Write("Vorname: ");
string vorname = Convert.ToString(Console.ReadLine());
Console.Write("Nachname: ");
string nachname = Convert.ToString(Console.ReadLine());
Console.Write("Adresse: ");
string adresse = Convert.ToString(Console.ReadLine());
string info = vorname + nachname + adresse;
return (info);
}
Method1也应该是静态的,因为您是从静态的Main调用的 Method1也应该是静态的,因为您是从静态的Main调用的 包含此代码的类名是什么?如果要从静态方法调用Method1,则Method1需要是静态的。Convert.ToString是不必要的,因为Console.ReadLine已经返回了一个字符串。您试图在哪里调用Method1()?包含此代码的类名是什么?如果要从静态方法调用Method1,则Method1需要是静态的。Convert.ToString是不必要的,因为Console.ReadLine已经返回了一个字符串。您试图在哪里调用Method1()?您需要将返回的值保存到一个变量,否则它将无法使用。实际上,不需要存储返回的值。您可以这样使用它:Console.WriteLine(Method1());如果你看一下OP的原始代码,你会发现“info”(大概是预期的返回值)被使用了两次,所以需要存储在变量中(调用method1两次会导致数据被输入两次)。是的,我同意OP想要存储他的方法的输出,但这仍然是不真实的“您需要将返回值保存到变量中,否则它将无法使用”。您需要将返回值保存到变量中,否则它将无法使用。实际上,不需要存储返回值。您可以这样使用:Console.WriteLine(Method1());如果您查看OP的原始代码,您将看到“info”(可能预期返回值)使用了两次-因此需要存储在变量中(调用method1两次将导致数据输入两次)。是的,我同意OP希望存储其方法的输出,但“您需要将返回值保存到变量中,否则无法使用”这一说法仍然不真实。