How to Inherit method but with different return type?

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

Given the following classes:

ClassA
{
     public ClassA DoSomethingAndReturnNewObject()
     {}    
}

ClassB : ClassA
{}

ClassC : ClassA
{}
10条回答
  •  生来不讨喜
    2021-01-17 19:25

    What you're describing is a covariant return type and is not supported in C#.

    However, you could create ClassA as an open generic and have the closed generic inheritors return their own type.

    Example:

    public abstract class ClassA where T: ClassA, new()
    {
        public abstract T DoSomethingAndReturnNewObject();
    }
    
    public class ClassB: ClassA
    {
        public override ClassB DoSomethingAndReturnNewObject()
        {
            //do whatever
        }
    }
    

提交回复
热议问题