Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 尽管已正确初始化对象,但仍引发System.NullReferenceException_C#_Exception_Object - Fatal编程技术网

C# 尽管已正确初始化对象,但仍引发System.NullReferenceException

C# 尽管已正确初始化对象,但仍引发System.NullReferenceException,c#,exception,object,C#,Exception,Object,我正在尝试为RPG编写一个清单系统。我有一个名为“Item”的自定义类型和一个名为“Bag”的类。可以使用此功能将物品放入袋子中: public Item aw = new Item(); public void PutIn(Item aw) { Contents[Index]=aw; Index++; } 当我用 Bag.PutIn(someItem); 在主代码中,它抛出System.NullReferenceException。 通过研究这个问题,我发现

我正在尝试为RPG编写一个清单系统。我有一个名为“Item”的自定义类型和一个名为“Bag”的类。可以使用此功能将物品放入袋子中:

public Item aw = new Item();
public void PutIn(Item aw)
{
    Contents[Index]=aw;
    Index++;        
}
当我用

Bag.PutIn(someItem);
在主代码中,它抛出System.NullReferenceException。
通过研究这个问题,我发现这通常是由不正确初始化对象引起的,但在本例中,我确实使用Item aw=new Item();;初始化了对象;。我做错了什么?

不是未初始化的项对象。您可能没有初始化“Contents”数组。

Contents[Index]=aw;正在引发System.NullReferenceException。如何初始化内容?我们需要查看更多代码,您包含的内容还不够。仅此而已。非常感谢。