• 获取实现了某接口的所有类,并返回该类中自定义的方法的方法名


    准备阶段:

      定义接口和实现接口的类。

        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();
  • 相关阅读:
    Lucky Substrings
    KMP
    圆桌问题(hdu4841)
    codeforces 624C Graph and String
    Joseph(hdu1443)
    The Longest Straight(FZUoj2216)
    C1. 组队活动 Small(BNUOJ)
    A1. 道路修建 Small(BNUOJ)
    Problem 2221 RunningMan(fuzoj)
    CODEFORCEs 621E. Wet Shark and Blocks
  • 原文地址:https://www.cnblogs.com/zhangchaoran/p/10103032.html
Copyright © 2020-2023  润新知