How do I define the return type of an interface method to be another interface?

后端 未结 6 1499
陌清茗
陌清茗 2021-02-02 18:09

I\'m new to interfaces and abstract classes. I want to create a couple of interfaces to define core methods and variables for the objects for a shopping cart system. Then I want

6条回答
  •  不思量自难忘°
    2021-02-02 18:49

    This is a matter of contra/covariance.

    2 changes are required to make this compile.

    1) Remove the "set" option on the property of the interface. (It's only implementing a get; property, which makes the most sense, in any case)

    2) Change Cart to:

    public abstract class Cart : ICart
    {

    private List _cartItems = new List();
    
    public List CartItems 
    { ...
    

    I also highly recommend changing your interface to expose IList instead of List. The design guidelines (and FxCop) recommend not exposing List in the public interface. List is an implementation detail - IList is the appropriate interface/return type.

提交回复
热议问题