Overriding an abstract property with a derived return type in c#

前端 未结 6 1705
独厮守ぢ
独厮守ぢ 2021-02-06 23:20

I have four classes. Request, DerivedRequest, Handler, DerivedHandler. The Handler class has a property with the following declaration:

public abstract Request         


        
6条回答
  •  长发绾君心
    2021-02-07 00:23

    This is not theoretically possible. The override must be covariant for return type (that is, the return type must be more specific or the same), and contravariant for parameter (that is, parameter type must be less specific or the same). So your new type must be effectively at the same time covariant and contravariant with respect to the Request -- that means, the only possible type is just Request.

    For this reason, it's not allowed in C# to change the type of properties for overrides.

提交回复
热议问题