问题
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 == "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)
回答1:
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";
}
}
.......
}
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/6988761/access-variable-from-other-namespaces