How to Inherit method but with different return type?

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

Given the following classes:

ClassA
{
     public ClassA DoSomethingAndReturnNewObject()
     {}    
}

ClassB : ClassA
{}

ClassC : ClassA
{}
10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-17 19:21

    Well, the correct answer is no and, generally, this is a bad idea. If you are returning something completely different, find another way.

    However, if you aren't returning something completely different, an interface can solve your issue. Instead of returning a class, return an interface and have classes A, B, and C return objects that implement that interface in the way they see fit.

提交回复
热议问题