How to Inherit method but with different return type?

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

Given the following classes:

ClassA
{
     public ClassA DoSomethingAndReturnNewObject()
     {}    
}

ClassB : ClassA
{}

ClassC : ClassA
{}
10条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-17 19:21

    I finally devised the following solution. For my case it's useful enough, but it assumes that ClassA knows about it's derivatives and is limited to those two options. Not really high-level thinking, but it works. :)

    ClassA
    {
        public ClassA DoSomethingAndReturnNewObject()
        {
            if (this.GetType() == typeOf(ClassB))
            {
                return new ClassB(values);
            }
            else
            {
                return new ClassC(values):
            }
        }    
    }
    
    ClassB : ClassA
    {}
    
    ClassC : ClassA
    {}
    

提交回复
热议问题