Passing variables from Main function to another C# class

前端 未结 4 646
轮回少年
轮回少年 2021-01-21 07:56

I\'m beating my head against the wall pretty severely with this. I have several variables inside a C# console application that I would like to re-use. However, I cannot for th

4条回答
  •  無奈伤痛
    2021-01-21 08:30

    The Program class is probably Static so you'll have to access those fields by class name instead of instance.

    class Program
    {
        public string Name = "a name";
    
        static void Main(string[] args)
        {
            Name = "Hello"; //You can't do this, compile error
            Program p = new Program();
            p.Name = "Hi"; //You can do this
    
            SecondName = "Sn"; //You can do this
            Program.SecondName = "Tr"; //You can do this too
        }
        public static string SecondName = "Peat";
    }
    

提交回复
热议问题