C#/문제해결

0317_ 인벤토리_개체 참조가 개체의 인스턴스로 설정되지 않았습니다.

minquu 2021. 3. 18. 01:01
반응형

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace study05_HW
{
    public class Inventory
    {
        public int capacity;
        public Item[] items;
        public int index;
        public Inventory(int capacity)
        {
            this.capacity = capacity;
            this.items = new Item[this.capacity];
        }
        public void Additem(Item item)
        {
            this.items[this.index] = item;
            Console.WriteLine("{0}인덱스에 {1}아이템을 넣었습니다.", this.index, item.GetName());
            this.index++;
        }
        public void Print()
        {
            foreach (Item itemprint in this.items) {
                Console.WriteLine("{0}, {1}", itemprint.GetName(), itemprint.GetItemType());
            }
        }
    }
}

 

 public void Print()
        {
            foreach (Item itemprint in this.items) {
                Console.WriteLine("{0}, {1}", itemprint.GetName(), itemprint.GetItemType());
            }

개체 참조가 개체의 인스턴스로 설정되지 않았습니다.  이 오류가 이해되지 않았습니다.  // 

이 말은 배열중에 널 값이 있을 경우 생기는 오류 였습니다.

 

해결 

----> if (itemprint != null) 의 조건문을 걸어주면 됩니다.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace study05_HW
{
    public class Inventory
    {
        public int capacity;
        public Item[] items;
        public int index;
        public Inventory(int capacity)
        {
            this.capacity = capacity;
            this.items = new Item[this.capacity];
        }
        public void Additem(Item item)
        {
            this.items[this.index] = item;
            Console.WriteLine("{0}인덱스에 {1}아이템을 넣었습니다.", this.index, item.GetName());
            this.index++;
        }
        public void Print()
        {
            foreach (Item itemprint in this.items)
            {
                if (itemprint != null)
                {
                    Console.WriteLine("{0}, {1}", itemprint.GetName(), itemprint.GetItemType());
                }
            }

        }
    }
}

 

 

반응형