码迷,mamicode.com
首页 > Windows程序 > 详细

C# 根据对象类完整名称,创建对象实例

时间:2014-11-22 07:03:32      阅读:273      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   sp   for   文件   

转自: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# 根据对象类完整名称,创建对象实例

标签:style   blog   http   io   ar   color   sp   for   文件   

原文地址:http://www.cnblogs.com/bluemaplestudio/p/4114612.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!