开发者

Access variable from other namespaces

I am trying to set/read a variable in class bluRemote from another namespace/class like so:

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

and the other cs file (which is the form):

namespace BluMote
{
    public partial class SettingsForm : Form
    {
        if (BluMote.bluRemote.cableOrSat == "CAB开发者_如何学编程LE")
        {
             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)


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.

So instead of making the bluRemote class static you keep it the same and do:

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 - i.e. 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. However, I would strongly suggest that:

  • You rename your class to follow .NET naming conventions
  • You don't make variables public; use properties

Also note that there's only one namespace here - 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.

If you declare the cableOrSat field as:

public static string cableOrSat = "CABLE";

You will be able to access it through the class name itself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜