How to access derived class members from an interface?

后端 未结 4 735
误落风尘
误落风尘 2021-01-07 12:26

I have three classes; Stamp, Letter and Parcel that implement an interface IProduct and they also have some of their own functionality.

public interface IP         


        
4条回答
  •  旧巷少年郎
    2021-01-07 12:40

    You can't access the additional members of classes which implement an interface because you're only exposing IProduct in the List of items. I'd add specific list types for each item in the shopping cart to the ShoppingCart class, and then you can expose a sequence of all the products in the cart for anything which only needs to use the IProduct interface:

    public class ShoppingCart
    {
        public IList Stamps { get; }
        public IList Letters { get; }
        public IList Parcels { get; }
    
        public IEnumerable Products
        {
            get
            {
                return this.Stamps.Cast()
                    .Concat(this.Letters.Cast())
                    .Concat(this.Parcels.Cast());
            }
        }
    }
    

提交回复
热议问题