如何解决字符串数组对象的NullReference异常?(How to resolve NullReference Exception on String Array Objects? [duplic

编程入门 行业动态 更新时间:2024-10-22 07:29:24
如何解决字符串数组对象的NullReference异常?(How to resolve NullReference Exception on String Array Objects? [duplicate])

这个问题在这里已有答案:

什么是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 answers

I 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 size

You 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

更多推荐

本文发布于:2023-08-04 23:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1423331.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字符串   如何解决   异常   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!