[英]C# Change a created objects value from another class
我有一个 Main.class,它在 5 秒时运行一个计时器(当它重置时,我想做一堆方法然后重复计时器)。 我有一个带有 currentReserve-property 的 Water.class 和一个带有 CurrentThirst 和 MaximumThirst-propertys 的 pop.class。 在 Pop 类中,我有一个在计时器重置时调用的方法。 基本上,我希望 popclass 消耗我在 Mainclass 中创建的对象中的 currentReserve-int。 我提供了必要的代码,并在调试器认为我错误的地方用注释标记:
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;
}
}
您有两次_water
成员:一次在AITest
,一次在Pop
类中。 只使用一个,然后传递它。 你得到的异常将是NullReferenceException
,因为没有任何东西分配给Pop._water
成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.