Sorry for the rookie question, as I'm just starting out with C#.
I have a class
namespace WindowsFormsApplication1
{
class people
{
public int Cash;
public string LastName;
public void GiveCash(int amount) { this.Cash = this.Cash - amount; }
public void ReceiveCash(int amount) { this.Cash = this.Cash + amount; }
}
}
and I initialize two object with it.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
people viktor = new people() { Cash = 1000, LastName = "Jushenko" };
people julia = new people() { Cash = 500, LastName = "Timoshenko" };
}
but later in the code I can not access any of those objects. For example I i use
pri开发者_开发百科vate void button1_Click(object sender, EventArgs e)
{ viktor.cash = 200; }
it says something like "The name 'victor' does not exist in this context..." what am I doing wrong?
Thanks!
You are declaring local variables in the Form1 constructor. You cannot access them after going out of scope. You should declare them as fields in the class, like this:
public partial class Form1 : Form
{
private people viktor;
private people julia;
public Form1()
{
InitializeComponent();
viktor = new people() { Cash = 1000, LastName = "Jushenko" };
julia = new people() { Cash = 500, LastName = "Timoshenko" };
}
The fields viktor
and julia
are now part of your class, and you can access them from your methods inside the class.
The scope of your victor
variable is local to the Form1
constructor and can't be accessed outside of it.
You need to promote it to be a field if you want to access it in the event handler:
private people viktor;
public Form1()
{
InitializeComponent();
viktor = new people() { Cash = 1000, LastName = "Jushenko" };
people julia = new people() { Cash = 500, LastName = "Timoshenko" };
}
private void button1_Click(object sender, EventArgs e)
{
viktor.cash = 200;
// Note: the "julia" variable is not in scope here.
}
There are different scopes that you need to be aware of. The reason why you cannot access your variables is because they are in a scope which you don't got access to.
One solution would be to move the variables out of their current scope:
public partial class Form1 : Form
{
private people victor = null;
private people julia = null;
public Form1()
{
InitializeComponent();
this.viktor = new people() { Cash = 1000, LastName = "Jushenko" };
this.julia = new people() { Cash = 500, LastName = "Timoshenko" };
}
....
精彩评论