准备阶段:
定义接口和实现接口的类。
interface IMyInterface { void Write(); } /// <summary> /// 实现类1 /// </summary> public class MyTest1 : IMyInterface { public MyTest1() { var methodNames = GetType().GetMethods().Select(m => m.Name).ToList(); } public void Write() { Console.WriteLine("这里是测试类 1"); } } /// <summary> /// 实现类2 /// </summary> public class MyTest2 : IMyInterface { public void Write() { Console.WriteLine("这里是测试类 2"); } public void MyMethod2() { Console.WriteLine("这里是测试类2 的第2个方法"); } }
定义执行方法(最后是调用)
/// <summary> /// 获取实现了某接口的类 /// </summary> /// <param name="iType"></param> public static void GetClasses(Type iType) {
Assembly asm = Assembly.GetExecutingAssembly(); //当前程序集
var types = asm.GetTypes().Where(t => t.GetInterfaces().Contains(iType)).ToList();
foreach(var t in types) { Console.WriteLine(t.FullName); Type tt = Type.GetType(t.FullName); IMyInterface my = Activator.CreateInstance(tt) as IMyInterface; //这里不应该把接口直接写进来的 my.Write(); var methodNames = tt.GetMethods().Select(m => m.Name).ToList(); Console.WriteLine("该类具有的方法名:"); List<string> oriNames = new List<string> { "ToString", "Equals", "GetHashCode", "GetType" }; methodNames = methodNames.Except(oriNames).ToList(); //但问题是你不知道方法名对应的功能是什么啊!!! foreach (var name in methodNames) { Console.WriteLine(" " + name); } Console.WriteLine(); } }
调用:
GetClasses(typeof(IMyInterface)); Console.ReadKey();