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

前端 未结 6 1840
独厮守ぢ
独厮守ぢ 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:22

    This isn't really a good way to structure things. Do one of the following

    1) Just don't change the return type, and override it normally in the subclass. In DerivedHandler you can return an instance of DerivedRequest using the base class signature of Request. Any client code using this can choose to cast it to DerivedRequest if they want to.

    2) Use generics instead if they are not supposed to be polymorphic.

    public abstract class HandlerBase where T: Request
    {
        public abstract T Request {get;set;}
    }
    
    public class Handler: HandlerBase()
    
    public class DerivedHandler: HandlerBase()
    

提交回复
热议问题