简体   繁体   English

从其他名称空间访问变量

[英]Access variable from other namespaces

I am trying to set/read a variable in class bluRemote from another namespace/class like so: 我正在尝试从另一个名称空间/类设置/读取类bluRemote中的变量,如下所示:

namespace BluMote
{
    class bluRemote
    {
        public string cableOrSat = "CABLE";
     ........
    }
}

and the other cs file (which is the form): 和另一个cs文件(形式):

namespace BluMote
{
    public partial class SettingsForm : Form
    {
        if (BluMote.bluRemote.cableOrSat == "CABLE")
        {
             BluMote.bluRemote.cableOrSat = "SAT";
        }
 .......
    }
}

I know i am doing it wrong but I'm more used to doing stuff like this in VB so its like night and day ha :o) 我知道我做错了,但是我更习惯在VB中做这样的事情,所以它就像黑夜一样:o)

What you are trying to do is work with static variables so you would need to change your class to this: 您想要做的是使用静态变量,因此您需要将类更改为:

namespace BluMote
{
    public static class bluRemote
    {
        public static string cableOrSat = "CABLE";
        ........
    }
}

It is better if you stay away from static classes (for the most part) and instead focus on an object oriented approach where you have an instance (object) of bluRemote. 最好是远离静态类(在大多数情况下),而专注于具有bluRemote实例(对象)的面向对象的方法。

So instead of making the bluRemote class static you keep it the same and do: 因此,与其将bluRemote类设为静态,不如将其保持不变并执行以下操作:

public partial class SettingsForm : Form
{
    private bluRemote _remote = new bluRemote();  // possibly created somewhere else

    public void SomeFunction() 
    {
        if (_remote.cableOrSat == "CABLE")
        {
             _remote.cableOrSat = "SAT";
        }
    }
    .......
}

You're trying to access an instance variable - ie one which has a potentially different value for each object - just by class name. 您正在尝试仅通过名访问实例变量(即,每个对象具有可能不同的值的实例变量)。 That only works for static variables. 这仅适用于静态变量。

You need to have an instance of bluRemote , and ask that for its value. 你需要有一个实例 bluRemote要求其价值。 However, I would strongly suggest that: 但是,我强烈建议:

  • You rename your class to follow .NET naming conventions 您重命名您的类以遵循.NET命名约定
  • You don't make variables public; 公开变量; use properties 使用属性

Also note that there's only one namespace here - BluMote . 还要注意,这里只有一个名称空间BluMote Both of your classes are declared in that namespace. 您的两个类都在该命名空间中声明。

As you've declared the cableOrSat field, you'll need to set it on an instance of the bluRemote class, but you are trying to set it using the name of the class itself. 声明cableOrSat字段后,需要在bluRemote类的实例上进行设置,但是您尝试使用类本身的名称进行设置。

If you declare the cableOrSat field as: 如果将cableOrSat字段声明为:

public static string cableOrSat = "CABLE";

You will be able to access it through the class name itself. 您将可以通过类名本身访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM