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


 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值