Passing variable values between methods…?

前端 未结 3 1913
我在风中等你
我在风中等你 2021-01-28 09:08

Can someone help me with passing values from one class method to another in c#. I\'ve tried looking it up, but I get lost in pages of code and I cant find a simple example. Take

3条回答
  •  失恋的感觉
    2021-01-28 09:57

    You could have the method return this value:

    public static string getName()
    {
        Console.Clear();
        Console.Write("Enter name: ");
        return Console.ReadLine();
    }
    

    and then in your main program call the method and store the result in a local variable:

    static void Main(string[] args)
    {
        string myName = Values.getName();
    }
    

    Notice that since getName is a static method you do not need to create an instance of the Values class in order to invoke it. You could directly call it on the type name.

    If on the other hand the getName method wasn't static:

    public string getName()
    {
        Console.Clear();
        Console.Write("Enter name: ");
        return Console.ReadLine();
    }
    

    then you need the instance:

    static void Main(string[] args)
    {
        Values values = new Values();
        string myName = values.getName();
    }
    

提交回复
热议问题