如何从我的方法中存储一些特定数据

时间:2013-01-01 22:31:42

标签: c# variables methods variable-assignment

我的程序有一些方法,其中一些是调用其他一些方法,我的问题是我想使用一个方法在以前的方法中生成的一些数据,我不知道我应该怎么做。

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.
        }      
   }
}

2 个答案:

答案 0 :(得分:3)

只需使用返回值:

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;
    }      
}

Methods

  

方法可以向调用者返回一个值。如果是返回类型,则为类型   在方法名称之前列出,不是void,那么该方法可以返回   使用return关键字的值。带有关键字的语句   返回后跟一个与返回类型匹配的值将返回   方法调用者的那个值......


由于您已经提到不能使用返回值,因此另一个选项是使用out parameter

public static void method1(string text)
{
   string letter;
   method2("some text", out letter);
   // now letter is "A"
}

public static void method2(string text, out string letter)
{
   // ...
   letter = "A";
}  

答案 1 :(得分:0)

您可以将值存储在类的成员变量中(在这种情况下必须是静态的,因为引用它的方法是静态的),或者您可以从method2返回值,并从method1里面调用method2你想用它。

我会让你知道如何编码它。