How to access derived class members from an interface?

后端 未结 4 708
误落风尘
误落风尘 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:55

    The reason why you can't access additional members from a derived class is that you are using the interface in the List<> - therefore you'll only be able to access properties on that interface.

    A pattern that might help you is the double-dispatch pattern.

    Example below:

    public interface IHandler
    {
        void Handle(Stamp stamp);
        void Handle(Letter letter);
        ...
    }
    
    public class Handler : IHandler
    {
        public void Handle(Stamp stamp)
        {
           // do some specific thing here...
        }
        public void Handle(Letter letter)
        {
           // do some specific thing here...
        }
        ...
    }
    
    public interface IProduct
    {
        string Name { get; }
        int Quantity { get; set; }
        float Amount { get; }
        void Handle(IHandler handler);
    }
    
    public class Stamp : IProduct
    {
        public string Name { get { return "Stamp"; } }
        public int Quantity { get; set; }
        public float Amount { get; set; }
        public float UnitPrice { get; set; }
        public void Handle(IHandler handler)
        {
             handler.Handle(this);
        }
    }
    

    You can now program some specific functionality in the Handler - I'm guessing you want to calculate some kind of total price given things such as quantity * unit price or a weight & destination lookup table...

提交回复
热议问题