【问题标题】:how to get all of the implemantations of an Interface using Reflection?如何使用反射获得接口的所有实现?
【发布时间】:2011-10-12 09:34:50
【问题描述】:
Public interface IRuleObject {}

Public class RuleBase : IRuleObject {}

Public class Length : RuleBase {}

Public class Range : RuleBase {}

Public class SetDefault : IRuleObject {}

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

正如您所注意到的,一些 Rules 可能源自实现 IRuleObjectRuleBase,还有一些其他的 Rules 不继承 RuleBase 并尝试自行实现 IRuleObject。上述所有规则都可以分配给IRuleObject

我试过了:

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

但它无法检索 规则
想法表示赞赏:-)
谢谢

【问题讨论】:

    标签: c# inheritance reflection interface implementation


    【解决方案1】:

    我认为你只是把 IsAssignableFrom 弄错了。试试:

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

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

    【讨论】:

    • 感谢乔恩,一如既往,你是救世主 :-)
    猜你喜欢
    • 1970-01-01
    • 2015-06-17
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 2010-09-21
    • 1970-01-01
    • 2021-09-26
    相关资源
    最近更新 更多