mercredi 12 août 2020

C# Trigger a function in a class by its name

I am trying to write code to check for requirements for a student before being allowed to register for classes. I want this requirements check to be dynamic, in case requirements change, or might need to add new requirements and only do the checks if this requirement is activated (maybe not all students need that requirement).

I created an interface with the types of requirements:

public interface IBasicRequirementsEvaluator
    {
        RequirementResult CheckForFiles();

        RequirementResult CheckForFinancialHold();

        RequirementResult CheckForRegistrationHold();

        RequirementResult CheckForStandingID();

        RequirementResult CheckForGraduationDate();
    }

and then their implementations:

public class BasicChecksImplementations : IBasicRequirementsEvaluator
    {
        private StudentData _data { get; set; }

        public BasicChecksImplementations(StudentData data)
        {
            data = _data;
        }


        [ActionName("CheckForFiles")]
        public RequirementResult CheckForFiles()
        {
            throw new NotImplementedException();
        }

        [ActionName("CheckForFinancialHold")]
        public RequirementResult CheckForFinancialHold()
        {
            throw new NotImplementedException();
        }

        [ActionName("CheckForGraduationDate")]
        public RequirementResult CheckForGraduationDate()
        {
            throw new NotImplementedException();
        }

        [ActionName("CheckForRegistrationHold")]
        public RequirementResult CheckForRegistrationHold()
        {
            throw new NotImplementedException();
        }

        [ActionName("CheckForStandingID")]
        public RequirementResult CheckForStandingID()
        {
            throw new NotImplementedException();
        }
    }

and then trying to perform checks only if the check is activated, by having the name of the requirement check present in a collection of strings:

public RequirementsResult CheckBasicRequirements (StudentData data, List<string> CheckActionNamesList)
        {
            RequirementsResult result = new RequirementsResult();
            BasicChecksImplementations checks = new BasicChecksImplementations(data);

            var methods = checks.GetType().GetMethods(BindingFlags.Public);

            foreach (string actionName in CheckActionNamesList)
            {
                var method = methods.Where(x => x.Name == actionName).FirstOrDefault();
                method.Invoke(this, null);
            }

            return result;
        }

But there is nothing in the variable methods, so obviously this is wrong. (also is there a design pattern that I could use to achieve this?).

Aucun commentaire:

Enregistrer un commentaire