Passing variable values between methods…?

前端 未结 3 1916
我在风中等你
我在风中等你 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:43

    First you need to actually store the variable somewhere. Right now it's a local variable in the method, so it will go away right after you have assigned the value to it.

    Make it a property in the class, and make the method an instance method instead of a static method:

    namespace simplecode
    {
        public class Values
        {
    
            public string MyName { get; set; }
    
            public void getName()
            {
                Console.Clear();
                Console.Write("Enter name: ");
                MyName = Console.ReadLine();
            }
        }
    }
    

    Now you can call the method and pick up the value afterwards:

    namespace simplecode
    {
    
        class Program
        {
            static void Main(string[] args)
            {
                Values myValues = new Values();
                myValues.getName();
                Console.WriteLine(myValues.MyName);
            }
        }
    }
    

提交回复
热议问题