How to Inherit method but with different return type?

前端 未结 10 990
北荒
北荒 2021-01-17 19:20

Given the following classes:

ClassA
{
     public ClassA DoSomethingAndReturnNewObject()
     {}    
}

ClassB : ClassA
{}

ClassC : ClassA
{}
10条回答
  •  余生分开走
    2021-01-17 19:43

    This isn't inheritance, because the return type of the method is part of its signature. You're not changing the method, you'd be creating an entirely new one.

    You do have some options. You could, for example, make the method DoSomethingAndReturnNewObject a generic-based method, and have it return its generic type. This is probably the most direct path to the exact behavior for which you're looking.

    The other alternative is to leave the method signatures as-is, and have the subclass methods return instances of ClassB and ClassC. Then the client code would need to be responsible for casting in order to use those objects as their appropriate derived classes.

    Is there some reason the common interface of ClassA doesn't suffice? Polymorphism will, if you have derived and overridden virtual members correctly, provide you with the correct functionality if you're only using the ClassA members.

提交回复
热议问题