Problem with Covariant return types from an abstract method

柔情痞子 提交于 2019-12-06 13:22:35

Justin I am a little bit confused why you need to go through all that trouble.

If you abstract method is of return type IQueryable<CandidateBase> then that's what you'll get. I don't see a problem with this, since later on you could still cast it back to CandidateA or CandidateB

So what exactly are you trying to achieve? Maybe I am not understanding you question.

Edit to add:

Justin, what about this?

public abstract class RecruiterBase<T>
    {
        // Constructors declared here

        public abstract IQueryable<CandidateBase> GetCandidates();
    }

    public abstract class CandidateBase
    {
        // Constructors declared here
    }


    public class CandidateA : CandidateBase
    {

    }

    public class RecruiterA : RecruiterBase<RecruiterA>
    {
        // Constructors declared here

        // ----HERE IS WHERE I AM BREAKING DOWN----
        public override IQueryable<CandidateBase> GetCandidates()
        {
            return db.Candidates.Where(cand => cand.RecruiterId == this.RecruiterId)
                         .Select(x => new CandidateA
                                          {
                                             CandidateId = c.CandidateId,
                                             CandidateName = c.CandidateName,
                                             RecruiterId = c.RecruiterId
                                           })
                         .Cast<CandidateBase>()
                         .AsQueryable();
        }
    }

I think your intentions are good, but the net result is that you're missing the point of polymorphic code and also losing the value.

The purpose of working with objects by their abstract type or by their interfaces is to allow you to work with any concrete implementation, without needing to know any concrete implementation details. I think your belief is that by returning concrete types you are producing higher-quality code, when in fact you're beginning to negate the value of the abstract base class by covering up the abstraction.

A properly built set of derived classes should have only very few needs to be addressed by their concrete types; the abstract class should suffice for working with all implementations and should handle the vast majority of work with those classes--the exceptions should be in the minority.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!