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

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

    Except for hiding the original property:

    public new DerivedRequest Request { get;set;}
    

    However, I strongly advise against that. Hiding something supposed to be overriden is inviting trouble, especially if the property isn't a simple auto generated one. Also, if using it as an interface or base class, the original implementation (in that case, one class higher in the inheritance tree). If you are implementing an abstract class or interface, you won't even be able to hide the original signature, as you are required to implement it.

    Usually, if you think about using the new keyword, you are on the wrong track. There are cases where it is necessary and required, however, in most cases, it isn't.

    Instead, make another property:

    public DerivedRequest DerivedRequest {/* make adequate conversions here*/ }
    

    That way, you are on the clear side concerning OOP and you get your information in a clear way.

提交回复
热议问题