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

前端 未结 7 1861
北海茫月
北海茫月 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:33

    Change your method signature on Derived class to:

     public override BaseReturnType PolymorphicMethod() 
     {
        return new DerivedReturnType();     
     }
    

    C# doesn't support variant return types. You can check out this post for a way to do this using Generics...http://srtsolutions.com/blogs/billwagner/archive/2005/06/17/covaraint-return-types-in-c.aspx

    Here's a sample using Generics in your model:

    public class BaseReturnType
    {
    }
    public class DerivedReturnType : BaseReturnType
    {
    }
    
    public abstract class BaseClass where T : BaseReturnType
    {
        public abstract T PolymorphicMethod();
    
    }
    
    public class DerviedClass : BaseClass
    {
        public override DerivedReturnType PolymorphicMethod()
        {
            throw new NotImplementedException();
        }
    }
    

提交回复
热议问题