C# 接口

时间:2019-11-16 14:01:09   收藏:0   阅读:82
 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();
            }
        }

 

 

原文:https://www.cnblogs.com/enych/p/11871506.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!