[英]C# Change a created objects value from another class
I have a Main.class which runs a timer at 5 seconds (when it resets i want to do a bunch of methods and then repeat the timer).我有一个 Main.class,它在 5 秒时运行一个计时器(当它重置时,我想做一堆方法然后重复计时器)。 I have a Water.class with a currentReserve-property and a pop.class with a CurrentThirst and MaximumThirst-propertys.
我有一个带有 currentReserve-property 的 Water.class 和一个带有 CurrentThirst 和 MaximumThirst-propertys 的 pop.class。 In the Pop class i have a method thats get called when the timer reset.
在 Pop 类中,我有一个在计时器重置时调用的方法。 Basically i want the popclass to consume the currentReserve-int in the object which i have created in the Mainclass.
基本上,我希望 popclass 消耗我在 Mainclass 中创建的对象中的 currentReserve-int。 I provide the essential code and mark with comments where the debugger thinks iam wrong:
我提供了必要的代码,并在调试器认为我错误的地方用注释标记:
public AITest()
{
public Water _water;
public Pop _pop;
Timer dayTimer = new Timer();
int timeLeft = 5;
public AITest()
{
InitializeComponent();
_water = new Water(8000);
lblWater.Text = _water.CurrentReserve.ToString();
_pop = new Pop(100, 100);
dayTimer.Interval = 1000;
dayTimer.Enabled = true;
dayTimer.Tick += dayTimer_Tick;
dayTimer.Start();
lblCountDown.Text = timeLeft.ToString();
}
private void dayTimer_Tick(object sender, EventArgs e)
{
lblCountDown.Text = timeLeft.ToString();
timeLeft -= 1;
if (timeLeft < 0)
{
timeLeft = 5;
_water.CurrentReserve += 100;
_pop.HaveToDrink();
lblWater.Text = _water.CurrentReserve.ToString();
}
}
}
}
public class Pop
{
public int CurrentThirst { get; set; }
public int MaximumThirst { get; set; }
public Water _water;
public Pop(int currentThirst, int maximumThirst)
{
CurrentThirst = currentThirst;
MaximumThirst = maximumThirst;
}
public void HaveToDrink()
{
CurrentThirst -= 30;
_water.CurrentReserve -= 30; //Here i get an error
}
}
public class Water
{
public int CurrentReserve { get; set; }
public Water(int currentReserve)
{
CurrentReserve = currentReserve;
}
}
You've got a _water
member twice: once in AITest
and once in the Pop
class.您有两次
_water
成员:一次在AITest
,一次在Pop
类中。 Use only one, and pass it around.只使用一个,然后传递它。 The exception you get will be a
NullReferenceException
, because nothing is ever assigned to the Pop._water
member.你得到的异常将是
NullReferenceException
,因为没有任何东西分配给Pop._water
成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.