有时候,为了快速批量处理已经实现某个基类或者某个接口的子类,需要通过反射的方式获取到他们的类类型(Type),然后再通过

1
Activator.CreateInstance(objType);

或者

1
Assembly.Load(path).CreateInstance(typeName);

或者

1
Assembly.LoadFile(filePath).CreateInstance(typeName);

创建对象实例。

以下通过一个简单的示例来展示:
1,获取当前程序集中的全部类型;
2,判断某一类型是否是继承与另一类型;
3,根据类型名动态创建对象。

目前还有个疑问,不知道谁能解答:
1,如何判断某个类是否实现了某个接口,目前只能先 new 一个对象,然后再 用 is 判断。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Diagnostics;
 
namespace com.hetaoos
{
 
    class Test
    {
        public Test()
        {
            var types = Assembly.GetExecutingAssembly().GetTypes();
            var baseType = typeof(BaseProcessor);
            List<BaseProcessor> processors = new List<BaseProcessor>();
            foreach (var t in types)
            {
                var tmp = t.BaseType;
                while (tmp != null)
                {
                    if (tmp == baseType)
                    {
                        BaseProcessor obj = MethodMaker.CreateObject(t.FullName) as BaseProcessor;
                        if (obj != null)
                        {
                            processors.Add(obj);
                        }
                        break;
                    }
                    else
                    {
                        tmp = tmp.BaseType;
                    }
                }
            }
 
            Debug.Print("Processor Count:{0}", processors.Count);
            foreach (var p in processors)
            {
                Debug.Print("{0}\t:{1}", p, p.Calc(2, 5));
            }
        }
    }
 
    public class MethodMaker
    {
 
        /// <summary>
        /// 创建对象(当前程序集)
        /// </summary>
        /// <param name="typeName">类型名</param>
        /// <returns>创建的对象,失败返回 null</returns>
        public static object CreateObject(string typeName)
        {
            object obj = null;
            try
            {
                Type objType = Type.GetType(typeName, true);
                obj = Activator.CreateInstance(objType);
            }
            catch (Exception ex)
            {
                Debug.Write(ex);
            }
            return obj;
        }
 
        /// <summary>
        /// 创建对象(外部程序集)
        /// </summary>
        /// <param name="path"></param>
        /// <param name="typeName">类型名</param>
        /// <returns>创建的对象,失败返回 null</returns>
        public static object CreateObject(string path, string typeName)
        {
            object obj = null;
            try
            {
 
                obj = Assembly.Load(path).CreateInstance(typeName);
            }
            catch (Exception ex)
            {
                Debug.Write(ex);
            }
 
            return obj;
        }
    }
 
    public abstract class BaseProcessor
    {
        public abstract int Calc(int a, int b);
    }
 
    public class Adder : BaseProcessor
    {
        public override int Calc(int a, int b)
        {
            return a + b;
        }
    }
 
    public class Multiplier : BaseProcessor
    {
        public override int Calc(int a, int b)
        {
            return a * b;
        }
    }
}

输出结果为:

1
2
3
Processor Count:2
com.hetaoos.Adder   :7
com.hetaoos.Multiplier  :10

PS:
判断某个类是否继承自某个接口、类的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public static bool IsParent(Type test, Type parent)
{
    if (test == null || parent == null || test == parent || test.BaseType == null)
    {
        return false;
    }
    if (parent.IsInterface)
    {
        foreach (var t in test.GetInterfaces())
        {
            if (t == parent)
            {
                return true;
            }
        }
    }
    else
    {
        do
        {
            if (test.BaseType == parent)
            {
                return true;
            }
            test = test.BaseType;
        } while (test != null);
 
    }
    return false;
}

C# 中反射获取某类的子类和根据类型名动态创建对象的更多相关文章

  1. java中的反射机制,以及如何通过反射获取一个类的构造方法 ,成员变量,方法,详细。。

    首先先说一下类的加载,流程.只有明确了类这个对象的存在才可以更好的理解反射的原因,以及反射的机制. 一.  类的加载 当程序要使用某个类时,如果该类还未被加载到内存中,则系统会通过加载,连接,初始化三 ...

  2. org.reflections 接口通过反射获取实现类源码研究

    org.reflections 接口通过反射获取实现类源码研究 版本 org.reflections reflections 0.9.12 Reflections通过扫描classpath,索引元数据 ...

  3. Java实现通过反射获取指定类的所有信息

    package com.ljy; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.l ...

  4. thinkphp模型中的获取器和修改器(根据字段名自动调用模型中的方法)

    thinkphp模型中的获取器和修改器(根据字段名自动调用模型中的方法) 一.总结 记得看下面 1.获取器的作用是在获取数据的字段值后自动进行处理 2.修改器的作用是可以在数据赋值的时候自动进行转换处 ...

  5. java-通过反射获取目标类的属性,方法,构造器

    首先定义一个urse package com.studay_fanshe; public class User { private String uname; private int age; pri ...

  6. 【Java基础】Java中如何获取一个类中泛型的实际类型

    泛型的术语 <>: 念做typeof List<E>: E称为类型参数变量 ArrayList<Integer>: Integer称为实际类型参数 ArrayLis ...

  7. Java中如何获取一个类中泛型的实际类型

    本文链接:https://blog.csdn.net/kuuumo/article/details/83021158   _______________________________________ ...

  8. C# 通过反射获取方法/类上的自定义特性

    1.所有自定义属性都必须继承System.Attribute 2.自定义属性的类名称必须为 XXXXAttribute 即是已Attribute结尾 自定义属性QuickWebApi [Attribu ...

  9. C#利用反射获取实体类的主键名称或者获取实体类的值

    //获取主键的 PropertyInfo PropertyInfo pkProp = ).FirstOrDefault(); //主键名称 var keyName=pkProp.Name; //实体类 ...

随机推荐

  1. 谈谈c#中异步编程模型的变迁

    大家在编程过程中都会用到一些异步编程的情况.在c#的BCL中,很多api都提供了异步方法,初学者可能对各种不同异步方法的使用感到迷惑,本文主要为大家梳理一下异步方法的变迁以及如何使用异步方法. Beg ...

  2. CefSharp .net

    构建基于Chromium的应用程序 chromium是google chrome浏览器所采用的内核,最开始由苹果的webkit发展而出,由于webkit在发展上存在分歧,而google希望在开发上有更 ...

  3. Android笔记——我的Android课的开始

    android 最底层的是什么?  硬件 介于硬件与软件之间的一个交互,你猜猜需要什么? 软件的上面一层便是各种的类库 硬件与软件之间的交互,就是需要驱动的进行. 1.android系统架构 1.Li ...

  4. js防止客户端多触发

    代码: /***防止多触发**id 必须唯一*fn 回掉函数*wait 延迟多长时间**使用例子:* ToPreventMoreTrigger('id', function () {//注意 id 是 ...

  5. SQL server 临时表

    创建临时表,#代表局部临时表,##代表全局临时表.局部临时表和全局临时表的具体含义是什么呢? 举例说明一下比较清晰些,先来看下局部临时表,[新建查询],在里面输入如下文本: 运行后,我们在此文件执行输 ...

  6. 类的继承和多态性-编写Java应用程序,定义Animal类,此类中有动物的属性:名称 name,腿的数量legs,统计动物的数量 count;方法:设置动物腿数量的方法 void setLegs(),获得腿数量的方法 getLegs(),设置动物名称的方法 setKind(),获得动物名称的方法 getKind(),获得动物数量的方法 getCount()。定义Fish类,是Animal类的子类,

    编写Java应用程序,定义Animal类,此类中有动物的属性:名称 name,腿的数量legs,统计动物的数量 count;方法:设置动物腿数量的方法 void setLegs(),获得腿数量的方法 ...

  7. 学习Data Science/Deep Learning的一些材料

    原文发布于我的微信公众号: GeekArtT. 从CFA到如今的Data Science/Deep Learning的学习已经有一年的时间了.期间经历了自我的兴趣.擅长事务的探索和试验,有放弃了的项目 ...

  8. Java 线程 — ConcurrentLinkedQueue

    ConcurrentLinkedQueue 在考虑并发的时候可以先考虑单线程的情况,然后再将并发的情况考虑进来. 比如ConcurrentLinkedQueue: 先考虑单线的offer 再考虑多线程 ...

  9. 使用SQL Server Audit记录数据库变更

        最近工作中有一个需求,就是某一个比较重要的业务表经常被莫名其妙的变更.在SQL Server中这类工作如果不事前捕获记录的话,无法做到.对于捕获变更来说,可以考虑的选择包括Trace,CDC. ...

  10. java中对象的初始化过程

    class Parent{ int num = 8;// ->3 Parent(){ //super(); // ->2 //显示初始化 // ->3 //构造代码段 // -> ...