1. 程式人生 > >C#的一段經典程式碼,查詢當前程式所有繼承或實現自指定類的子類。

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