1. 程式人生 > >C# 根據物件類完整名稱,建立物件例項

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;
        }