有什么想法为什么这个静态类没有初始化?

0 c# static records

我目前正在为一个涉及构建"tamagotchi"程序的uni项目开发一个程序,但是我很早就遇到了与我用于存储与每个宠物相关的值的类构造相关的错误.记录的一部分.但是,当我跟踪程序时,变量似乎没有初始化,并且NullReferenceException一旦程序第一次调用变量就会抛出变量.有什么想法吗?

static class GlobalVars     // Static class used to store pet values as 'global' variables.
{
    public static TTamagotchiPet Pet1 { get; set; }
    public static TTamagotchiPet Pet2 { get; set; }
    public static TTamagotchiPet Pet3 { get; set; }
    public static TTamagotchiPet Pet4 { get; set; }
}

public void frmTamagotchi_Load(object sender, EventArgs e)      // On Load event; initialises Pet 1.
{
    tmrUpdate.Enabled = true;
    GlobalVars.Pet1.Active = true;
    //GlobalVars.Pet1.Dead = false;
    //GlobalVars.Pet1.FunValue = 0;
    //GlobalVars.Pet1.FoodValue = 0;
    //GlobalVars.Pet1.HealthValue = 0;
    //GlobalVars.Pet1.ExertionValue = 0;
    //GlobalVars.Pet2.Active = false;
    //GlobalVars.Pet3.Active = false;
    //GlobalVars.Pet4.Active = false;
}

private void tmrUpdate_Tick(object sender, EventArgs e)     // Update timer. Each tick reduces pet attributes and checks to see if a pet has died, and controls pet states for the animation timer.
{
// First section updates pet attributes and checks to see if health reaches the 100 limit - at which point the pet dies.
    if (GlobalVars.Pet1.Active == true)  //code crashes here
    {
        if (GlobalVars.Pet1.Dead == false)
        {
Run Code Online (Sandbox Code Playgroud)

代码还会跳过剩余的初始化(我在方法中注释掉了很多行frmTamagotchi_load),即使这些行被取消注释; 这可能与这个问题有关吗?

Roy*_*tus 7

您永远不会为宠物自己设置值.

您需要将以下内容放在Load方法或构造函数中:

GlobalVars.Pet1 = new TTamagotchi();
GlobalVars.Pet2 = new TTamagotchi();
GlobalVars.Pet3 = new TTamagotchi();
GlobalVars.Pet4 = new TTamagotchi();
Run Code Online (Sandbox Code Playgroud)

在程序开始时,这些Pet1 ... Pet4值为null,除非您显式实例化它们,否则保持不变,如上面的代码所示.

如果将此代码放在构造函数中,请确保它是一个类static,就像GlobalVars一个static类一样.


Ode*_*ded 6

您需要以某种方式初始化属性.因为它们没有被设置为任何东西,它们将默认为null,意味着任何访问成员的尝试都将导致a NullReferenceException.

一个静态构造函数会做的伎俩:

static class GlobalVars     // Static class used to store pet values as 'global' variables.
{
    static GlobalVars
    {
      Pet1 = new TTamagotchi();
      Pet2 = new TTamagotchi();
      Pet3 = new TTamagotchi();
      Pet4 = new TTamagotchi();
    }

    public static TTamagotchiPet Pet1 { get; set; }
    public static TTamagotchiPet Pet2 { get; set; }
    public static TTamagotchiPet Pet3 { get; set; }
    public static TTamagotchiPet Pet4 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)