0

I have an error in the following implementation. It says that OnlineWebStore_Process cannot implement the interface IWebStore because they don't have a matching return type. But the method returns Item which implements the IItem interface used as return type in the IWebStore interface. What's a good solution to this problem?

public interface IItem
{
    string id { get; set; }
    string name { get; set; }
}

public interface IWebStore
{
    List<IItem> GetOnlineItems();
}

public class Item : IItem
{
    public Item(string _id)
    {
        id = _id;
    }

    public string id { get; set; }
    public string name { get; set; }
}

public class OnlineWebStore_Process : IWebStore
{
    public List<Item> GetOnlineItems()
    {
        List<Item> items = new List<Item>();

        return items
    }
}
4

4 回答 4

5
public class OnlineWebStore_Process : IWebStore
{
    public List<IItem> GetOnlineItems()
    {
        List<IItem> items = new List<IItem>();

        return items;
    }
}

Your method signature has to be exactly the same, you can't take a subclass instead. If you do return a subclass you're losing a part of your abstraction and the interface contract is broken.

于 2013-10-22T17:20:55.263 回答
3

GetOnlineItems() should return List<IItem>

于 2013-10-22T17:21:14.423 回答
1
public List<Item> GetOnlineItems()
{
    List<Item> items = new List<Item>();

    return items
}

Here you return List instead of List. This way you don't have your IWebStore method implemented. Here is the correct way:

public List<IItem> GetOnlineItems()
{
    List<IItem> items = new List<IItem>();
    items.Add( new Item( "1" ) ); // Adding an instance, which implements the interface IItem

    return items;
}
于 2013-10-22T17:26:48.003 回答
0

Firstly you method signatures need to be same. And secondly List<Item> is not child of List<IItems> like Item and IItem. They are totally different type.

于 2013-10-22T17:27:34.590 回答