C# 中反射获取某类的子类和根据类型名动态创建对象
有时候,为了快速批量处理已经实现某个基类或者某个接口的子类,需要通过反射的方式获取到他们的类类型(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:2com.hetaoos.Adder :7com.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# 中反射获取某类的子类和根据类型名动态创建对象的更多相关文章
- java中的反射机制,以及如何通过反射获取一个类的构造方法 ,成员变量,方法,详细。。
首先先说一下类的加载,流程.只有明确了类这个对象的存在才可以更好的理解反射的原因,以及反射的机制. 一. 类的加载 当程序要使用某个类时,如果该类还未被加载到内存中,则系统会通过加载,连接,初始化三 ...
- org.reflections 接口通过反射获取实现类源码研究
org.reflections 接口通过反射获取实现类源码研究 版本 org.reflections reflections 0.9.12 Reflections通过扫描classpath,索引元数据 ...
- Java实现通过反射获取指定类的所有信息
package com.ljy; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.l ...
- thinkphp模型中的获取器和修改器(根据字段名自动调用模型中的方法)
thinkphp模型中的获取器和修改器(根据字段名自动调用模型中的方法) 一.总结 记得看下面 1.获取器的作用是在获取数据的字段值后自动进行处理 2.修改器的作用是可以在数据赋值的时候自动进行转换处 ...
- java-通过反射获取目标类的属性,方法,构造器
首先定义一个urse package com.studay_fanshe; public class User { private String uname; private int age; pri ...
- 【Java基础】Java中如何获取一个类中泛型的实际类型
泛型的术语 <>: 念做typeof List<E>: E称为类型参数变量 ArrayList<Integer>: Integer称为实际类型参数 ArrayLis ...
- Java中如何获取一个类中泛型的实际类型
本文链接:https://blog.csdn.net/kuuumo/article/details/83021158 _______________________________________ ...
- C# 通过反射获取方法/类上的自定义特性
1.所有自定义属性都必须继承System.Attribute 2.自定义属性的类名称必须为 XXXXAttribute 即是已Attribute结尾 自定义属性QuickWebApi [Attribu ...
- C#利用反射获取实体类的主键名称或者获取实体类的值
//获取主键的 PropertyInfo PropertyInfo pkProp = ).FirstOrDefault(); //主键名称 var keyName=pkProp.Name; //实体类 ...
随机推荐
- Android SDK content Loader has encountered a problem.parseSdkContent failed
打开Eclipse,弹出Android SDK content Loader has encountered a problem.parseSdkContent failed,当点击detail按钮, ...
- 使用后台服务数据更新UI
https://www.websmithing.com/2011/02/01/how-to-update-the-ui-in-an-android-activity-using-data-from-a ...
- ECMAScript5 Object的新属性方法
虽然说现在并不是所有的浏览器都已经支持ECMAScript5的新特性,但相比于ECMAScript4而言ECMAScript5被广大浏览器厂商广泛接受,目前主流的浏览器中只有低版本的IE不支持,其它都 ...
- Visual Studio 2015速递(3)——ASP.NET 新特性
系列文章 Visual Studio 2015速递(1)——C#6.0新特性怎么用 Visual Studio 2015速递(2)——提升效率和质量(VS2015核心竞争力) Visual Studi ...
- IOS 公共类-数字处理
1.写一个方法,调用的时候交换两个数的值 -(void) swap:(int*)a andNumber:(int*)b{ int temp = *a; *a = *b; *b = temp; } 调用 ...
- iOS-国家气象局-天气预报接口等常用接口
接口地址: http://www.weather.com.cn/data/sk/101010100.html http://www.weather.com.cn/data/cityinfo/10101 ...
- Netty学习五:Buffers
1. Netty中的缓冲 在Netty中并没有使用Java自带的ByteBuffer,而是自己实现提供了一个缓存区来用于标识一个字节序列,并帮助用户操作原始字节或者自定义的POJO. Java NIO ...
- 部署到IIS报错:HTTP错误500.19,错误代码0x800700d
title=部署到IIS报错:HTTP错误500.19,错误代码0x800700d. 用vs直接运行网站没问题,部署到IIS就报错,由此可知应该是IIS中不支持网站相关配置. 查找发现在web.c ...
- Java并发包中CyclicBarrier的工作原理、使用示例
1. CyclicBarrier的介绍与源码分析 CyclicBarrier 的字面意思是可循环(Cyclic)使用的屏障(Barrier).它要做的事情是,让一组线程到达一个屏障(也可以叫同步点)时 ...
- java中paint方法和paintComponent方法的不同
/* 1.由Component.java源代码中可以看见其中的paint()方法体是空的,在Container中重写了该方法,其子类Window等也重写了该方法 2.由JComponent.java源 ...