C#的一段经典代码,查找当前程序所有继承或实现自指定类的子类。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace FWJB_S.Test
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             var helloType = typeof(Hello);
14 
15             List<Type> types = new List<Type>();
16 
17             foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
18             {
19                 foreach (var type in assembly.GetTypes())
20                 {
21                     if (helloType.IsAssignableFrom(type))
22                     {
23                         if (type.IsClass && !type.IsAbstract)
24                         {
25                             types.Add(type);
26                         }
27                     }
28                 }
29             }
30             types.ForEach((t) =>
31             {
32                 var helloInstance = Activator.CreateInstance(t) as Hello;
33 
34                 helloInstance.Say();
35             });
36 
37             Console.ReadKey();
38         }
39 
40         public interface Hello
41         {
42             void Say();
43         }
44 
45         public class A : Hello
46         {
47             public void Say()
48             {
49                 Console.WriteLine("Say Hello to A");
50             }
51         }
52 
53         public class B : Hello
54         {
55             public void Say()
56             {
57                 Console.WriteLine("Say Hello to B");
58             }
59         }
60     }
61 }

简单强大,此处假设我们要调用所有继承自Hello接口的Say方法。 类A 和 类B可以不在当前程序集,只要当前应用程序加载了它所在的程序集就行。

在我们项目分层的时候,有时候在应用层要做一些配置,但具体配置需要到不同的类库才能决定,我们应用层肯定会依赖各个类库,于是就可以在核心层创建这么一个Hello接口,各个层都会依赖于核心层(相当于公共层),各个层去实现这个Hello接口完成配置,最后我们在应用层的时候只需要查找所有继承自Hello接口的Type 创建他们的实例然后调用它们的Say方法。更多应用还等你去发现。

posted @ 2018-10-09 14:00  Gxqsd  阅读(1698)  评论(0编辑  收藏  举报