将值赋给属性时出现空错误

时间:2015-10-14 07:59:57

标签: c# oop

尝试创建一个允许我在记录中拾取错误的自定义对象。

public class gridIntegerField
{
    private int value;
    private bool isValid;
    private string message;



    public int Value
    {
        get { return this.value; }
        set { this.value = value; }
    }
    public bool IsValid
    {
        get { return isValid; }
        set { isValid = value; }
    }
    public string Message
    {
        get { return message; }
        set { message = value; }
    }


}

public class gridRecord    
{
    private gridIntegerField printRun;

    public gridIntegerField PrintRun
    {
      get { return printRun; }
      set { printRun = value; }
    }

}

创建对象并尝试设置值时,我得到以下错误...

未处理的类型' System.NullReferenceException'发生在XML-Console.exe

创建对象的代码......

gridRecord spr = new gridRecord();
spr.PrintRun.Value = 200;
spr.PrintRun.IsValid = true;
spr.PrintRun.Message = "No Errors";

Console.WriteLine(spr.PrintRun.Value.ToString());
Console.WriteLine(spr.PrintRun.IsValid.ToString());
Console.WriteLine(spr.PrintRun.Message.ToString());
Console.ReadKey();

错误发生在这行代码

spr.PrintRun.Value = 200;

1 个答案:

答案 0 :(得分:0)

因为在printRun实例化后没有实例化gridRecord字段。

您可以在构造函数方法中执行此操作。

public class gridRecord    
{
    private gridIntegerField printRun;

    public gridIntegerField PrintRun
    {
      get { return printRun; }
      set { printRun = value; }
    }

    //Add a constructor method
    public gridRecord()
    {
       //and instantiate the printRun.
       printRun = new gridIntegerField();
    }    
}