C# 如何存储方法中的特定数据
我的程序有一些方法,其中一些是调用其他一些方法。我的问题是,我想使用一个方法在以前的方法中生成的一些数据,我不知道该怎么做C# 如何存储方法中的特定数据,c#,variables,methods,variable-assignment,C#,Variables,Methods,Variable Assignment,我的程序有一些方法,其中一些是调用其他一些方法。我的问题是,我想使用一个方法在以前的方法中生成的一些数据,我不知道该怎么做 namespace MyProg { public partial class MyProg: Form { public static void method1(string text) { //procedures method2("some text"); /
namespace MyProg
{
public partial class MyProg: Form
{
public static void method1(string text)
{
//procedures
method2("some text");
// Here i want to use the value from string letter from method2.
}
public static void method2(string text)
{
//procedures
string letter = "A"; //Its not A its based on another method.
}
}
}
只需使用返回值:
public partial class MyProg: Form
{
public static void method1(string text)
{
string letter = method2("some text");
// Here i want to use the value from string letter from method2.
}
public static string method2(string text)
{
string letter = "A"; //Its not A its based on another method.
return letter;
}
}
方法可以向调用方返回值。如果返回类型为
在方法名称之前列出,不为void,则该方法可以返回
使用return关键字的值。带有关键字的语句
return后跟与返回类型匹配的值将返回
将该值传递给方法调用方
因为您已经提到不能使用返回值,所以另一个选项是使用
只需使用返回值:
public partial class MyProg: Form
{
public static void method1(string text)
{
string letter = method2("some text");
// Here i want to use the value from string letter from method2.
}
public static string method2(string text)
{
string letter = "A"; //Its not A its based on another method.
return letter;
}
}
方法可以向调用方返回值。如果返回类型为
在方法名称之前列出,不为void,则该方法可以返回
使用return关键字的值。带有关键字的语句
return后跟与返回类型匹配的值将返回
将该值传递给方法调用方
因为您已经提到不能使用返回值,所以另一个选项是使用
您可以将该值存储在类的成员变量中(在本例中,该变量必须是静态的,因为引用它的方法是静态的),也可以从method2返回该值,然后从method1内部调用method2
我将让您自己决定如何对其进行编码。您可以将值存储在类的成员变量中(在本例中,该变量必须是静态的,因为引用它的方法是静态的),也可以从method2返回值,然后从method1内部调用method2
我将让您自己决定如何编码。是的,但我的方法不能更改为静态字符串。它需要是静态无效的,无论哪种方式,我都不能在此时使用返回值。@Incognito:另一种方法是使用
out
-参数,并编辑我的答案。非常感谢,这将很好地完成工作,虽然我的值是3步深,但我遵循了你的示例,你也使用了很好的格式。是的,但我的方法不能更改为静态字符串,它需要是静态无效的,无论哪种方式,我都不能在此时使用返回值。@Incognito:另一种方法是使用out
-参数,编辑我的答案。非常感谢,这将很好地完成工作,虽然我的值是3步深,但我遵循了您的示例,您也使用了很好的格式。