本文介绍了实例化数组中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在尝试实例化一个新对象并将该对象存储到数组中.我收到对象引用未设置为对象的实例".我无法弄清楚我做错了什么,对我来说看起来很对.任何帮助将不胜感激.

Hi,

I''m trying to Instantiate a new object and store the object into an array. I am receiving "Object reference not set to an instance of an object." I can''t figure out what I''ve done wrong, it looks right to me. Any help is greatly appreciated.

MyExcel[] myexcel = null;
int excel = 0;
...
foreach (KeyValuePair<string, string> kvp in Common.divisionDictionary)
{
    myexcel[excel] = new MyExcel();         // Instantiate an instance of Excel

    path = Common.SpreadsheetDirectory;
    ...
}


我收到以下错误:


I''m receiving the error on:

myexcel[excel] = new MyExcel();



但是,如果我这样分配它,则效果很好:



However if I assign it like this it works perfect:

MyExcel Excel = new MyExcel();



谢谢
Glenn



Thank you,
Glenn

推荐答案

MyExcel[] myexcel = null;

...

myexcel[excel] = new MyExcel();         // Instantiate an instance of Excel


您不能将项目存储到不存在的数组中.您需要为myexcel分配一些条目-至少与foreach循环中遇到的条目一样.


You cannot store an item into an array that does not exist. You need to allocate some entries to myexcel - at least as many as will be encountered in your foreach loop.


MyExcel[] myexcel = null;


到(说)


to (say)

MyExcel[] myexcel = new MyExcel[10];



会修复您的程序.
:)



would fix your program.
:)


这篇关于实例化数组中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 12:32