简体   繁体   English

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

[英]How can i store some specific data from my methods

My program is having some methods and some of them are call some other methods my problem is that i want to use some data that a method is generating in a previous method and i dont know how im supposed to do that. 我的程序中有一些方法,其中一些被称为其他方法。我的问题是我想使用某个方法在先前方法中生成的某些数据,而我不知道该怎么做。

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

Just use return values: 只需使用返回值:

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 方法

Methods can return a value to the caller. 方法可以将值返回给调用方。 If the return type, the type listed before the method name, is not void, then the method can return the value using the return keyword. 如果返回类型(在方法名称之前列出的类型)不为空,则该方法可以使用return关键字返回值。 A statement with the keyword return followed by a value that matches the return type will return that value to the method caller... 带有关键字return且后跟匹配返回类型的值的语句将把该值返回给方法调用者...


Since you've mentioned that you cannot use return values, another option is to use an out parameter . 由于您已经提到不能使用返回值,因此另一个选择是使用out参数

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

You can either store the value in a member variable of the class (which in this case must be static since the method referring to it is static), or you can return the value from method2, and call method2 from inside method1 where you want to use it. 您可以将值存储在类的成员变量中(在这种情况下,该变量必须是静态的,因为引用它的方法是静态的),也可以从method2返回该值,然后从要在method1内部调用method2。用它。

I'll leave it up to you to figure out how to code it. 我将由您自己决定如何进行编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM