C# 根據對象類完整名稱,建立對象執行個體

來源:互聯網
上載者:User

標籤: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# 根據對象類完整名稱,建立對象執行個體

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.