T must be contravariantly valid

前端 未结 3 1503
灰色年华
灰色年华 2020-12-01 11:44

What is wrong with this?

interface IRepository where T : IBusinessEntity
{
    IQueryable GetAll();
    void Save(T t);
    void Delete         


        
3条回答
  •  旧巷少年郎
    2020-12-01 12:21

    Consider what would happen if the compiler allowed that:

    interface IR
    {
        void D(T t);
    }
    
    class C : IR
    {
        public void D(Mammal m)
        {
            m.GrowHair();
        }
    }
    ...
    IR x = new C(); 
    // legal because T is covariant and Mammal is convertible to Animal
    x.D(new Fish()); // legal because IR.D takes an Animal
    

    And you just tried to grow hair on a fish.

    The "out" means "T is only used in output positions". You are using it in an input position.

提交回复
热议问题