How to return subtype in overridden method of subclass in C#?

前端 未结 7 1856
北海茫月
北海茫月 2020-12-09 14:59

I have a subclass with an over-ridden method that I know always returns a particular subtype of the return type declared in the base class. If I write the code this way, it

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 15:52

    You can do this if you introduce an extra method to override (since you can't override and new a method with the same name in the same type):

    abstract class BaseClass
    {
        public BaseReturnType PolymorphicMethod()
        { return PolymorphicMethodCore();}
    
        protected abstract BaseReturnType PolymorphicMethodCore();
    }
    
    class DerivedClass : BaseClass
    {
        protected override BaseReturnType PolymorphicMethodCore()
        { return PolymorphicMethod(); }
    
        public new DerivedReturnType PolymorphicMethod()
        { return new DerivedReturnType(); }
    }
    

    Now you have a PolymorphicMethod method at each level with the correct type.

提交回复
热议问题