Programming Serendipity

気まぐれに大まかに生きるブログ

特定のインターフェースを実装するクラスのインスタンスのリストを取得する

github.com

を実装するときに調べたものです。 関数オブジェクトを使うときに、使える候補を自動で列挙する役割があります。

public static List<T> GetAllClassInstancesImplement<T>() where T : class
{
    var tmp = new List<T>();
    var alltypes = System.Reflection.Assembly.GetExecutingAssembly().GetTypes().Where(x => x.GetInterfaces().Contains(typeof(T)));
    alltypes.ToList().ForEach(x => tmp.Add(System.Activator.CreateInstance(x) as T));
    
    return tmp;
}

// how to use
var allInstances = GetAllClassInstancesImplement<ISomeInterface>();