C# 根据对象类完整名称,创建对象实例
2014-11-22 01:58
197 查看
转自:http://blog.csdn.net/mm33211/article/details/8143890
C# 根据对象类完整名称,创建对象实例
/// <summary> /// 根据指定的类全名,返回对象实例 /// </summary> /// <param name="objFullName">对象完整名称(包名和类名),如:com.xxx.Test</param> public object createObjectInstance(string objFullName) { //获取当前目录 string currentDir = Assembly.GetExecutingAssembly().Location; currentDir = currentDir.Substring(0, currentDir.LastIndexOf('\\')); DirectoryInfo di = new DirectoryInfo(currentDir); //获取当前目录下的所有DLL文件 FileInfo[] files = di.GetFiles("*.dll");//只查.dll文件 //遍历所有文件,查找需要对象的实现定义 Type type = Type.GetType(objFullName); if (type == null) { foreach (FileInfo fi in files) { type = getObjectType(fi.FullName, objFullName); if (type != null) { break; } } } if (type == null) { //throw new Exception("can not find class define of " + objFullName); return null; } //将对象实例化 object obj=Activator.CreateInstance(type); return obj; } /// <summary> /// 从DLL文件中查找指定的对象定义 /// </summary> /// <param name="dllFile">DLL文件路径</param> /// <param name="objFullName">对象完整名称(包名和类名),如:com.xxx.Test</param> /// <returns>如果找到,返回其对应的Type;如果没找到,则返回null</returns> private Type getObjectType(string dllFile, string objFullName) { Type type = Assembly.LoadFile(dllFile).GetType(objFullName); if (type != null) { Console.WriteLine("find obj in dll[" + dllFile + "]"); return type; } return null; }
相关文章推荐
- C# 根据对象类完整名称,创建对象实例
- C#根据类名称创建类的实例
- c#根据字符串创建对象实例
- C# 根据类名创建类的实例对象
- 详解C# 利用反射根据类名创建类的实例对象
- C#中根据类的名称字符串创建类的实例
- C# 利用反射根据类名创建类的实例对象
- 如何根据数组类型名称创建数组实例?
- C#根据类名称创建类的实例
- C# Type.GetConstructor() 根据构造函数参数获取实例对象(一)
- SQLServer获得所有用户存储过程、根据存储过程名称获得内容、获得数据库对象创建脚本
- C# 反射创建对象,包括创建引用外部程序集类的实例
- [C#]根据类的名称创建类
- C# 类反射创建对象实例
- C#文件监控对象FileSystemWatcher实例,文件创建,修改,删除,重命名等
- C# 中反射获取某类的子类和根据类型名动态创建对象(转载)
- C# 中反射获取某类的子类和根据类型名动态创建对象(转载)
- javascript的自定义实例对象竟然跟C#的创建对象如此相近
- More Effective C# 第21条、第22条 实例代码解析(可比较 可排序 自定义对象集合完整演示) IEquatable, IComparable,IEnumerable
- VS 2005中使用C#创建及调用WebService完整实例