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

前端 未结 6 1025
栀梦
栀梦 2020-11-27 10:36

Under a given namespace, I have a set of classes which implement an interface. Let\'s call it ISomething. I have another class (let\'s call it CClass

6条回答
  •  温柔的废话
    2020-11-27 11:06

    A working code-sample:

    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
    }
    

    Edit Added a check for a parameterless constructor so that the call to CreateInstance will succeed.

提交回复
热议问题