dimanche 11 avril 2021

Limiting types in C#

Context

I have a Question class . It has three subclasses:

  • ChoiceQuestion
  • ShortTextQuestion
  • LongTextQuestion

I have a Repository class which has an IEnumerable<Question>.


Code

class Question {}
class ChoiceQuestion : Question {}

class ShortTextQuestion : Question {}

class LongTextQuestion : Question {}

class Repository
{
    IEnumerable<Question> Question { get; set; }
}

Problem

I want to pick few questions for a Questionnaire from these repositories.

I have an IQuestionnaireBuilder which has an AddSource() method that helps configure which repository to pick questions from and how to pick them. I have the QuestionnaireSource class which holds this configuration.

Currently, I'm able to specify, which repository to pick from, how many questions to pick of each difficulty. I want to specify that it should only pick questions which are of specific subtypes. For instance, the questions to be picked must be either ChoiceQuestion or ShortTextQuestion. I've come across System.Type, but I want to restrict the types such that they must derive from Question.


Code

interface IQuestionnaireBuilder
{
    IQuestionnaireBuilder AddSource(Action<QuestionnaireSource> source);
}
class QuestionnaireSource
{
    public Repository Repository { get; set; }

    public IDictionary<QuestionDifficulty, int> { get; set; }
    
    // <Property/method to configure which subclasses to include, they must derive from Question>
}
enum QuestionDifficulty
{ Easy, Medium, Hard }
    IQuestionnaireBuilder builder = new QuestionnaireBuilder();
    
    Repository repo1 = someExternalProvider.GetRepo(1);
    Repository repo2 = someExternalProvider.GetRepo(2);
    builder
        .AddSource(source => {
            source.Repository = repo;
            source.Count["Easy"] = 10;
            source.Count["Medium"] = 7;
            source.Count["Hard"] =  3;
            source.PickOnlySpecificSubclassesOfQuestion() // how to implement this? 
       })
       .AddSource(source => {
            source.Repository = repo;
            source.Count["Easy"] = 30;
            source.Count["Medium"] = 15;
            source.Count["Hard"] =  5;
            source.PickOnlySpecificSubclassesOfQuestion() // how to implement this? 
       })    

Can anyone recommend a good approach?

Aucun commentaire:

Enregistrer un commentaire