将值赋给属性时出现空错误(Null error when assigning value to property)
尝试创建一个自定义对象,允许我在记录中拾取错误。
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; } } }当创建对象并尝试设置值时,我得到以下错误...
XML-Console.exe中发生了未处理的“System.NullReferenceException”类型异常
创建对象的代码......
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;Trying to create a custom object that will allow me to pickup errors in the records.
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; } } }when creating object and trying to set the values i get the folowing error...
An unhandled exception of type 'System.NullReferenceException' occurred in XML- Console.exe
Code for creating object...
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();the error happens at this line of code
spr.PrintRun.Value = 200;最满意答案
因为在gridRecord实例化之后你没有实例化printRun字段。
您可以在构造函数方法中执行此操作。
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(); } }Because you do not instantiate the printRun field after gridRecord instantiating.
You can do it in the constructor method.
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(); } }更多推荐
发布评论