Reference variable from a different method, class,

2020-05-09 22:30发布

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.

Basic structure I have:

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

And I need to access that variable from a completely different file. I have looked at several questions already posted here but not of them deal with the exact level I am trying to access or how to access the variable from a method with parameters that I cannot access at that time.

标签: c#
4条回答
乱世女痞
2楼-- · 2020-05-09 22:49

Can this not be done with a public property?

public class Service
{
    public bool MyVariable { get; set; }
    public bool AddRoute(l, m, n)
    {
        MyVariable = xyz;
    }
}  
查看更多
【Aperson】
3楼-- · 2020-05-09 22:53

I hope i will not confuse you even more.

The "variable in the other class" should be a property of that class. You need to make sure it is public, and then, you need the AddRoute method get an instance of that class with that property set. You could then access the property value using something like otherClassInstance.xyz.

If the above confuses you, I suggest starting at the beginning, learning about Object Oriented Programming before attempting any coding at all.

查看更多
手持菜刀,她持情操
4楼-- · 2020-05-09 22:58

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)
{
  // ...
}
查看更多
闹够了就滚
5楼-- · 2020-05-09 23:04

In your case, you can set that variable as return parameter of your method:

namespace Planning
{
    public class Service
    {
        public bool AddRoute()
        { 
            bool variable = true;
            return variable;
        }
    }
}

Call from different class:

namespace Planning
{
    public class AnotherClass
    {
        public void DoSomething()
        {
            Service service = new Service();
            bool otherVariable = service.AddRoute();
        }
    }
}

Now value of your variable from AddRoute method is inside otherVariable in another class.

查看更多
登录 后发表回答