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

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

    In the C# language you are not allowed to change the signature of an inherited method, unless you substitute it with another method with the same name. This technique is referred to as "member hiding" or "shadowing".

    If you are using .NET 2.0 or later, you could solve this problem by turning the return type of the Request property into a generic type parameter of the Handler class. The DerivedHandler class would then specify the DerivedRequest class as argument for that type parameter.

    Here's an example:

    // Handler.cs
    public class Handler where TRequest : Request
    {
        public TRequest Request { get; set; }
    }
    
    // DerivedHandler.cs
    public class DerivedHandler : Handler
    {
    }
    

提交回复
热议问题