Why an inherited interface can't be converted to its base interface in generic context?

前端 未结 2 1136
广开言路
广开言路 2020-12-04 03:22

I\'m trying to implement an interface inheritance system in my C# project, but I can\'t get it to work.

Here is a simplified version:



        
2条回答
  •  死守一世寂寞
    2020-12-04 03:55

    Let's have a play with your types and call them something different.

    public interface IFruit { }
    
    public abstract class BowlOf where Fruit : IFruit
    {
        public void Add(Fruit fruit) { }
    }
    
    public class Apple : IFruit { }
    
    public class BowlOfApples : BowlOf { }
    

    Now, with that - which is pretty much just a rename of the types (but changing public interface ChildInterface : BaseInterface {} to public class Apple : IFruit { }) then we create the following issue.

    Let's say I have public class Banana : IFruit { } also and let's assume that the following is legal:

    BowlOf c = new BowlOfApples();
    

    Then I am perfectly fine to call c.Add(new Banana()). What!?! You can't add a banana to a bowl of apples.

    And that's why the compiler is complaining when you try to do AbstractClass c = new ConcreteClass();.

提交回复
热议问题