代码之家  ›  专栏  ›  技术社区  ›  pitaridis

接口对象的调用方法

  •  1
  • pitaridis  · 技术社区  · 6 年前

    我有以下界面:

    public interface IPropertyEditor
    {
        string GetHTML();
        string GetCSS();
        string GetJavaScript();
    }
    

    我要获取从IPropertyEditor继承的所有类,并调用这些方法并获取返回值。

    我一直在努力,我所做的最好的搜索是以下。

    var type = typeof(IPropertyEditor);
    var types = AppDomain.CurrentDomain.GetAssemblies()
        .SelectMany(s => s.GetTypes())
        .Where(p => type.IsAssignableFrom(p));
    
    foreach (var item in types)
    {
        string html = (string)item.GetMethod("GetHTML").Invoke(Activator.CreateInstance(item, null), null);
    }
    

    问题是它引发了以下异常:

    MissingMethodException: Constructor on type 'MyAdmin.Interfaces.IPropertyEditor' not found.
    

    我认为CreateInstance方法认为该类型是一个类,并试图创建一个实例,但它失败了,因为该类型是一个接口。

    我如何解决这个问题?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Camilo Terevinto Chase R Lewis    6 年前

    你需要豁免 IPropertyEditor (本身) types

    var type = typeof(IPropertyEditor);
    var types = AppDomain.CurrentDomain.GetAssemblies()
        .SelectMany(s => s.GetTypes())
        .Where(p => p.IsClass && !p.IsAbstract && type.IsAssignableFrom(p));
    
    foreach (var item in types)
    {
        string html = (string)item.GetMethod("GetHTML").Invoke(Activator.CreateInstance(item, null), null);
    }
    

    如果确定没有抽象方法,也可以使用

    .Where(p => p != type && type.IsAssignableFrom(p));
    
        2
  •  2
  •   Nkosi    6 年前

    过滤器将包括接口。确保筛选的类型是类而不是抽象的,以确保可以初始化它。

    .Where(p => 
        p.IsClass &&
        !p.IsAbstract &&
        type.IsAssignableFrom(p));
    

    另外,基于所使用的激活器,假设被激活的类有一个默认的构造函数。