Type helloType = typeof(Hello); //Hello是一个接口 List<Type> types = new List<Type>(); //遍历程序集 foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { //遍历程序集类型 foreach (var type in assembly.GetTypes()) { if (helloType.IsAssignableFrom(type)) //判断类 是否 继承接口了 { if (type.IsClass && !type.IsAbstract) { types.Add(type); } } } } //执行继承 接口类的方法 for (int i = 0; i < types.Count; i++) { Hello helloInstance = Activator.CreateInstance(types[i]) as Hello; helloInstance.Say(); } //lanmuda表达式执行 types.ForEach( (t) => { var helloInstance = Activator.CreateInstance(t) as Hello; helloInstance.Say(); }); Console.ReadKey();
public interface Hello { void Say(); } public class A : Hello { public void Say() { Console.WriteLine("Say Hello to A"); Console.ReadLine(); } } public class B : Hello { public void Say() { Console.WriteLine("Say Hello to B"); Console.ReadLine(); } }