Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

c# - Cannot convert 'Item[]' to 'Item'

In this question I need to use a method 'AddItem' (found in an other .cs called Inventory) to add each item in my 'StoreStartingItem' array to the store's inventory.

I've tried simply calling the method and running the array through it like this:

Inventory.AddItem(StoreStartingItems);

However, I keep getting an error 'Argument 1: cannot convert from 'Shop.Item[]' to 'Shop.Item'.

I've tried changing my 'AddItem' method from using a class parameter to a class array parameter like this:

public bool AddItem(Item item)
        {
            if (mItems == null)
                return true;
            else
                return false;
        }

To this:

public bool AddItem(Item[] item)
        {
            if (mItems == null)
                return true;
            else
                return false;
        }

But then I'm getting an error 'An object reference is required for the non-static field, method, or property 'Inventory.AddItem(Item[])''.

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It appears like AddItem takes an Item but you are passing it an array of Item (Item[])

Try this:

foreach (var item in StoreStartingItems)
    Inventory.AddItem(item)

As mentioned in comments, you may want to read up more on C# and Object Orientated Programming first or follow some tutorials.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...