利用反射获取到实现当前接口的类,

本文只做代码验证,无任何实际意义

具体代码如下

 1 namespace General.Cons
 2 {
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             //假设从接口程序集中获得到的类集合
 8             List<Type> lstTypeClass = new List<Type>
 9             {
10                 typeof(Student),  typeof(StudentNo)
11             };
12 
13             Type oInterfaceType = typeof(IStudent);
14 
15             //在类集合中找到集成当前接口的类  集合
16             var lstTypeClassTmp = lstTypeClass.Where(x => x.GetInterface(oInterfaceType.Name) != null).ToList();
17             if (lstTypeClassTmp.Any())
18             {
19                 foreach (var item in lstTypeClassTmp)
20                 {
21                     //如果当前类获取到的接口等于遍历的接口名称,则匹配成功,
22                     if (item.GetInterface(oInterfaceType.Name).Equals(oInterfaceType))
23                     {
24                         Console.WriteLine(item.Name);
25                     }
26                 }
27                
28             }
29 
30             Console.WriteLine("Hello World!");
31             Console.ReadKey();
32         }
33     }
34 
35     public interface IStudent {
36         string GetName();
37     }
38     public class Student : IStudent
39     {
40         public string GetName()
41         {
42             return "Name";
43         }
44     }
45     public class StudentNo:IStudent
46     {
47         public string GetName()
48         {
49             return "Name";
50         }
51     }
52 }

 

posted on 2018-07-28 15:25  高兴happy  阅读(175)  评论(0编辑  收藏  举报