簡體   English   中英

如何找到實現給定接口的所有類?

[英]How to find all the classes which implement a given interface?

在給定的命名空間下,我有一組實現接口的類。 我們稱之為ISomething 我有另一個類(讓我們稱之為CClass ),它知道ISomething但不知道實現該接口的類。

我希望CClass能夠查找ISomething所有實現,實例化它的實例並執行該方法。

有沒有人知道如何用C#3.5做到這一點?

一個有效的代碼示例:

var instances = from t in Assembly.GetExecutingAssembly().GetTypes()
                where t.GetInterfaces().Contains(typeof(ISomething))
                         && t.GetConstructor(Type.EmptyTypes) != null
                select Activator.CreateInstance(t) as ISomething;

foreach (var instance in instances)
{
    instance.Foo(); // where Foo is a method of ISomething
}

編輯添加了對無參數構造函數的檢查,以便對CreateInstance的調用成功。

您可以使用以下命令獲取已加載程序集的列表:

Assembly assembly = System.Reflection.AppDomain.CurrentDomain.GetAssemblies()

從那里,您可以獲得程序集中的類型列表(假設公共類型):

Type[] types = assembly.GetExportedTypes();

然后,您可以通過在對象上查找該接口來詢問每種類型是否支持該接口:

Type interfaceType = type.GetInterface("ISomething");

不確定是否有更有效的方法來做反射。

使用Linq的一個例子:

var types =
  myAssembly.GetTypes()
            .Where(m => m.IsClass && m.GetInterface("IMyInterface") != null);
foreach (Type t in Assembly.GetCallingAssembly().GetTypes())
{
    if (t.GetInterface("ITheInterface") != null)
    {
        ITheInterface executor = Activator.CreateInstance(t) as ITheInterface;
        executor.PerformSomething();
    }
}

您可以使用以下內容並根據您的需要進行定制。

var _interfaceType = typeof(ISomething);
var currentAssembly = System.Reflection.Assembly.GetExecutingAssembly();
var types = GetType().GetNestedTypes();

foreach (var type in types)
{
    if (_interfaceType.IsAssignableFrom(type) && type.IsPublic && !type.IsInterface)
    {
        ISomething something = (ISomething)currentAssembly.CreateInstance(type.FullName, false);
        something.TheMethod();
    }
}

此代碼可以使用一些性能增強,但它是一個開始。

也許我們應該這樣做

foreach ( var instance in Assembly.GetExecutingAssembly().GetTypes().Where(a => a.GetConstructor(Type.EmptyTypes) != null).Select(Activator.CreateInstance).OfType<ISomething>() ) 
   instance.Execute(); 

暫無
暫無

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

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