这个问题在这里已有答案:
什么是NullReferenceException,我该如何解决? 33个答案我在类中有一个String array对象,即我想在运行时初始化的String[] particulars 。 相同的代码段适用于另一个不是数组的类对象。 这里nd是类的对象。
int i=0; foreach (DataRow row1 in dt1.Rows) { nd.particulars[i] = row1["floor"].ToString(); nd.quantity[i] = (double)row1["area"]; nd.rate[i] = (double)row1["rate"]; nd.amount[i] = (double)row1["amount"]; i++; }
以下代码抛出一些NullReferenceException 。 错误说:
你调用的对象是空的。
类定义如下:
class NoteDetails { public string[] particulars; public double[] quantity; public double[] rate; public double[] amount; public string[] mparticulars; public double[] mquantity; public double[] mrate; public double[] mamount; public NoteDetails() { particulars = null; quantity = null; amount = null; rate = null; mparticulars = null; mquantity = null; mamount = null; mrate = null; } }请告诉我我做错了什么?
This question already has an answer here:
What is a NullReferenceException, and how do I fix it? 31 answersI have a String array object in a class, i.e, String[] particulars which I want to initialize during runtime. The same code segment worked for another class object which was not array though. Here nd is an object of class.
int i=0; foreach (DataRow row1 in dt1.Rows) { nd.particulars[i] = row1["floor"].ToString(); nd.quantity[i] = (double)row1["area"]; nd.rate[i] = (double)row1["rate"]; nd.amount[i] = (double)row1["amount"]; i++; }
The following code is throwing some NullReferenceException. The error says:
Object reference not set to an instance of an object.
The class definition is as:
class NoteDetails { public string[] particulars; public double[] quantity; public double[] rate; public double[] amount; public string[] mparticulars; public double[] mquantity; public double[] mrate; public double[] mamount; public NoteDetails() { particulars = null; quantity = null; amount = null; rate = null; mparticulars = null; mquantity = null; mamount = null; mrate = null; } }Please tell me what I'm doing wrong?
最满意答案
您必须初始化您的字符串数组(以及您的其他数组)。 您可以在类的构造函数上执行此操作。
nd.particulars = new string[5]; //or whatever sizeYou have to initialize your string array (and your others arrays too). You can do that on the constructor of the class.
nd.particulars = new string[5]; //or whatever size更多推荐
发布评论