如何使用Reflection获取接口的所有实现?

时间:2011-07-25 08:11:44

标签: c# inheritance reflection interface implementation

Public interface IRuleObject {}

Public class RuleBase : IRuleObject {}

Public class Length : RuleBase {}

Public class Range : RuleBase {}

Public class SetDefault : IRuleObject {}

我正在尝试编写一段代码,在其中我可以获得所有实现的类 IRuleObject ...

正如您所注意到的,某些规则可能来自实施 IRuleObject RuleBase ,还有一些其他规则不继承 RuleBase 并尝试自己实现 IRuleObject 。上面的所有规则都可以分配给 IRuleObject

我试过了:

Assembly dll = Assembly.GetAssembly(typeof(IRuleObject));
var rules = dll.GetTypes().Where(x => x.IsAssignableFrom(typeof(IRuleObject)));

然而,它无法检索规则
我们赞赏这些想法:-)
感谢

1 个答案:

答案 0 :(得分:3)

我认为你刚刚以错误的方式得到了IsAssignable。尝试:

var rules = dll.GetTypes()
               .Where(x => typeof(IRuleObject).IsAssignableFrom(x));

当涉及泛型时,这种事情会让很多变得棘手,但在你的情况下它应该足够简单。