从 Main() 函数内的方法调用值

本文关键字:方法 调用 函数 Main | 更新日期: 2023-09-27 18:35:21

我正在尝试从 Main() 方法中调用一个名为 GetInputstring 的方法的值,然后继续执行后续步骤。我被困在如何获得价值myInt并继续前进。

Main()

中的 myInt(周围有两个 *)是它获得错误的地方。

    static void Main(string[] args)
    {
        GetInputstring(**myInt**);
        if (**myInt** <= 0)
        {
            Write1(**myInt**);
        }
        else
        {
            Write2(**myInt**);
        }
        Console.ReadKey();
    }
    public int GetInputstring(int myInt)
    {
        string myInput;
        //int myInt;
        Console.Write("Please enter a number: ");
        myInput = Console.ReadLine();
        myInt = Int32.Parse(myInput);
        return myInt;            
    }
    static void Write1(int myInt)
    {
        while (myInt <= 0)
        {
            Console.WriteLine("{0}", myInt++);
        }
    }
    static void Write2(int myInt)
    {
        while (myInt >= 0)
        {
            Console.WriteLine("{0}", myInt--);
        }
    }

从 Main() 函数内的方法调用值

MyInt 是你的参数(你传递给方法的值),它没有初始化。此外,您没有捕获返回值(应该是myInt)

您还需要将方法设为静态,以便从静态方法调用它们,或者创建类的实例并在其上调用该方法

这就是你得到你想要的东西的方式:

static void Main(string[] args)
{
    int myInt = GetInputstring(); //MyInt gets set with your return value 
    if (myInt <= 0)
    {
        Write1(myInt);
    }
    else
    {
        Write2(myInt);
    }
    Console.ReadKey();
}
public static int GetInputstring() //Deleted parameter because you don't need it.
{
    string myInput;
    //int myInt;
    Console.Write("Please enter a number: ");
    myInput = Console.ReadLine();
    int myInt = Int32.Parse(myInput);
    return myInt;            
}

您需要初始化myInt变量并将其存储在局部或全局范围内。使用此变量,您需要使用从GetInputString()获得的值来设置它,因为您没有将 int 作为ref传递它也不会在方法中分配。您还需要使方法成为静态方法,以便可以从Main调用它们而无需创建实例,例如:public static int GetInputstring()

int myInt = 0;
myInt = GetInputstring(myInt);
if (myInt <= 0)
{
    Write1(myInt);
}
else
{
    Write2(myInt);
}
Console.ReadKey();

或者(最好),您可以GetInputString()分配值,因为它不需要myInt作为参数传递。

static void Main(string[] args)
{
    int myInt = GetInputstring();
    if (myInt <= 0)
    {
        Write1(myInt);
    }
    else
    {
        Write2(myInt);
    }
    Console.ReadKey();
}
public static int GetInputstring()
{
    Console.Write("Please enter a number: ");
    string myInput = Console.ReadLine();
    return Int32.Parse(myInput);            
}