How to Inherit method but with different return type?

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

Given the following classes:

ClassA
{
     public ClassA DoSomethingAndReturnNewObject()
     {}    
}

ClassB : ClassA
{}

ClassC : ClassA
{}
10条回答
  •  温柔的废话
    2021-01-17 19:26

    You need to create a protected virtual method for the DoSomethingAndReturnNewObject to use:

    class ClassA
    {
        protected virtual ClassA Create()
        {
            return new ClassA()
        }
    
        public ClassA DoSomethingAndReturnNewObject()
        {
            ClassA result = Create();
            // Do stuff to result
            return result;
        }
    }
    
    class ClassB : ClassA
    {
         protected override ClassA Create() { return new ClassB(); }
    }
    
    class ClassC : ClassA
    {
         protected override ClassA Create() { return new ClassC(); }
    }
    

    Note the return type remains ClassA but the object instance type will be the specific class.

提交回复
热议问题