簡體   English   中英

接口對象的調用方法

[英]Call Method of interface object

我有以下界面:

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方法認為該類型是一個類並嘗試創建一個實例,但是由於該類型是一個接口,所以它失敗了。

我該如何解決這個問題?

過濾器將包含界面。 確保過濾的類型是類而不是抽象的,以確保可以對其進行初始化。

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

同樣基於所使用的激活器,該假設是被激活的類具有默認構造函數。

您需要從types免除IPropertyEditor (本身)

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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM