很抱歉新手问题,因为我刚刚开始使用C#。
我有一个班级
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; }
}
}
我用它初始化了两个对象。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
people 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; }
它说“在这种背景下不存在名字'胜利者'......”我做错了什么?
谢谢!
答案 0 :(得分:3)
您在Form1构造函数中声明局部变量。超出范围后,您无法访问它们。您应该将它们声明为类中的字段,如下所示:
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" };
}
字段viktor
和julia
现在是您班级的一部分,您可以从班级内的方法访问它们。
答案 1 :(得分:1)
victor
变量的范围是Form1
构造函数的本地范围,无法在其外部访问。
如果要在事件处理程序中访问它,则需要将其提升为字段:
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.
}
答案 2 :(得分:1)
您需要注意不同的范围。您无法访问变量的原因是因为它们位于您无法访问的范围内。
一种解决方案是将变量移出当前范围:
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" };
}
....