Reference variable from a different method, class, file

后端 未结 4 1690
余生分开走
余生分开走 2021-01-29 10:54

I need to reference the value of a variable in a different method, class, and file than the one I am currently in. I am brand new to C# and still trying to get these concepts.

4条回答
  •  不要未来只要你来
    2021-01-29 11:47

    Short answer: you can't, period.

    What you can do is set a public member variable:

    namespace Planning
    {
        public class Service
        {
            public bool variable;
    
            public bool AddRoute(l, m, n)
            { 
                variable = xyz;
            }
        }
    }
    

    But public member variables are frowned-upon, with good reason.

    Better yet, add a read-only property that returns the value of a private member variable:

    namespace Planning
    {
        public class Service
        {
            private bool variable;
    
            public bool Variable
            {
              get 
              {
                return variable;
              }
            }
    
            public bool AddRoute(l, m, n)
            { 
                variable = xyz;
            }
        }
    }
    

    Then from elsewhere:

    Planning.Service myObj = new Planning.Service();
    myObj.AddRoute(1,2,3);
    
    if (myObj.Variable)
    {
      // ...
    }
    

提交回复
热议问题