提问人:Daniel Robert 提问时间:1/26/2015 最后编辑:MirodinhoDaniel Robert 更新时间:1/26/2015 访问量:1234
发生“System.NullReferenceException”类型的未经处理的异常 [重复]
An unhandled exception of type 'System.NullReferenceException' occurring [duplicate]
问:
在下面的代码中,我在 finally 语句的第一行 - invoice[x] 上收到 null 引用错误。IdNumber = idResult;当我尝试为它分配一个值时,它怎么能给我一个空引用?
class Program
{
static void Main(string[] args)
{
const int theConst = 999;
Invoice[] invoice = new Invoice[5];
int x;
int idResult = 999;
int dayResult = 1;
double dResult = 0.0;
string checker;
for (x = 0; x < invoice.Length; ++x) //for loop to instantiate objects and obtain data
{
try
{
Console.Write("Enter invoice number ");
checker = Console.ReadLine();
if (int.TryParse(checker, out idResult))
{
idResult = Convert.ToInt32(checker);
}
else
{
idResult = theConst;
}
Console.Write("Enter balance ");
checker = Console.ReadLine();
if (double.TryParse(checker, out dResult))
{
dResult = Convert.ToDouble(checker);
}
else
{
dResult = 0.0;
}
Console.Write("Enter due day ");
checker = Console.ReadLine();
if (int.TryParse(checker, out dayResult))
{
dayResult = Convert.ToInt32(checker);
}
else
{
dayResult = 1;
}
invoice[x] = new Invoice(idResult, dResult, dayResult);
}
catch (Exception ex)
{
Console.WriteLine("enters catch x is " + x);
idResult = theConst;
dResult = 0.0;
dayResult = 1;
Console.WriteLine(ex.Message + "default value will be used");
}
finally
{
invoice[x].IdNumber = idResult;
invoice[x].BalanceDue = dResult;
invoice[x].DayDue = dayResult;
}
}
Console.WriteLine("Entered Invoices: " + Environment.NewLine);
for (x = 0; x < invoice.Length; ++x) //first display
{
Console.Write("#" + invoice[x].IdNumber + " $" + invoice[x].BalanceDue + " day " + invoice[x].DayDue + "\n");
}
Console.Read();
}
}
class Invoice
{
private int idNumber;
public int IdNumber
{
get
{
return idNumber;
}
set
{
idNumber = value;
}
}
private double balanceDue;
public double BalanceDue
{
get
{
return balanceDue;
}
set
{
balanceDue = value;
}
}
private int dayDue;
public int DayDue
{
get
{
return dayDue;
}
set
{
dayDue = value;
}
}
public Invoice(int num, double balance, int daydue)
{
IdNumber = num;
BalanceDue = balance;
DayDue = daydue;
Console.WriteLine(num + " " + balance + " " + daydue);
if (daydue < 1 || daydue > 31)
{
throw new ArgumentException("Day must be between 1-31 ");
}
if (num < 100 || num > 999)
{
throw new ArgumentException("ID number must be between 100-999 ");
}
}
public Invoice() : this(999, 0, 1) { }
}
}
答:
0赞
Mirodinho
1/26/2015
#1
此错误仅在运行时在初始化对象之前在尝试块中抛出异常时发生:即 invoice[x] = new Invoice(...); 因此,如果尝试块在未引发异常的情况下执行,则不会出现错误。请记住,“finally”中的代码无论是否发生错误都会执行。
您应该做的是初始化 Invoice 对象数组中的 5 个对象。
包括以下内容:
for (int z=0; z < invoice.Length; z++)
invoice[z] = new Invoice(idResult,dResult,dayResult);
在进入 for 循环之前。否则,该对象不会初始化,因此它没有属性。
这可能是可能更简单的解决方案之一。
评论