how to get all of the implemantations of an Interface using Reflection?
Public interface IRuleObject {}
Public class RuleBase : IRuleObject {}
Public class Length : RuleBase {}
Public class Range : RuleBase {}
Public class SetDefault : IRuleObject {}
I'm t开发者_JAVA百科rying to write a piece of code in which I can get all of the classes that implement IRuleObject...
As you noticed, some Rules might be derived from RuleBase which implements the IRuleObject and there are some other Rules which don't inherit the RuleBase and try implement the IRuleObject on their own. All of the Rules above are assignable to IRuleObject.
I tried :
Assembly dll = Assembly.GetAssembly(typeof(IRuleObject));
var rules = dll.GetTypes().Where(x => x.IsAssignableFrom(typeof(IRuleObject)));
However it couldn't retrieve the Rules
ideas are appreciated :-) thanksI think you've just got IsAssignableFrom the wrong way round. Try:
var rules = dll.GetTypes()
.Where(x => typeof(IRuleObject).IsAssignableFrom(x));
This sort of thing gets a lot trickier when generics are involved, but in your case it should be simple enough.
精彩评论