c# - How to get all classes that implement same interface? -


i have design issue. want have separate class every validation. also, want have 1 class call validations. idea if need new validation, add new validation class , works. don't need change else, add new class. this:

    public interface ivalidate{         bool validate();     }      public class validator1 : ivalidate{             public bool validate(){                  //do validation 1         }     }     public class validator2 : ivalidate{             public bool validate(){                  //do validation 2         }     }     //...     public class validatorn : ivalidate{             public bool validate(){                  //do validation n         }     }     //...................................     public interface ivalall{         bool validate_all();     }     public class validateall : ivalall{         public bool validate_all(){                   //call validators implements ivalidate interface             //do validation 1,2...n             //if validations return true, function return true.              //else return false.         }     } 

i don't know if best approach, idea want. problem don't know how implement validate_all() method.

how classes implement same interface , validation in 1 loop?

idea inject ivalall interface , validation 1 call. also, if think design not good, please feel free tell me. can change approach if have better idea.

you can inject classes implementing ivalidate via constructor injection class responsible validating them all:

public class ultimatevalidator {     private ivalidate[] validators      public ultimatevalidator(ivalidate[] validators)     {          this.validators = validators;     }      public bool validateall()     {           foreach (var validator in validators)           {                  if (validator.validate())                  {                       // etc.                  }           }     } } 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -