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方法。更多應用還等你去發現。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM