从不同的方法、类、文件引用变量

本文关键字:文件 引用 变量 方法 | 更新日期: 2023-09-27 18:05:33

我需要在不同的方法、类和文件中引用变量的值,而不是当前所处的方法、类和文件。我是c#的新手,还在努力理解这些概念。

基本结构:

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

我需要从一个完全不同的文件访问这个变量。我已经看了几个问题已经张贴在这里,但他们没有处理我试图访问的确切级别或如何从一个方法访问变量与参数,我当时无法访问。

从不同的方法、类、文件引用变量

我希望我不会让你更困惑。

"另一个类中的变量"应该是该类的属性。你需要确保它是公共的,然后,你需要AddRoute方法获得那个类的一个实例并设置那个属性。然后,您可以使用类似otherClassInstance.xyz的命令访问属性值。

如果上面的内容让你感到困惑,我建议你从头开始,在尝试任何编码之前先学习面向对象编程。

这难道不能用公共属性实现吗?

public class Service
{
    public bool MyVariable { get; set; }
    public bool AddRoute(l, m, n)
    {
        MyVariable = xyz;
    }
}  

简短的回答:你不能,句号。

可以设置public成员变量:

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

但是公共成员变量是不被允许的,这是有充分理由的。

更好的是,添加一个只读属性,返回私有成员变量的值:

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

Then from other:

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

在您的例子中,您可以将该变量设置为方法的返回参数:

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

从不同的类调用:

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

现在AddRoute方法中变量的值在另一个类的otherVariable中