C# 通过反射获取特性

  /// <summary>
        /// 通过反射获取特性
        /// </summary>
        /// <param name="className"></param>
        /// <returns></returns>
        public string GetTableNameByClassName(string className)
        {
            //获取当前应用程序(解决方案)的所有程序集
            Assembly[] appAssemblies = AppDomain.CurrentDomain.GetAssemblies();
            //过滤出当前应用程序下的自定义的程序集(解决方案下的所有项目) 建议:自己创建的项目建议统一一个前缀,这样才能进行过滤
            List<string> filterAssemblies = appAssemblies.Where(x=>x.FullName.StartsWith("你的项目前缀"))
                                                         .Select(e=>e.FullName).ToList();
            for (int i = 0;i< filterAssemblies.Count;i++)
            {
                //加载程序集
                Assembly currentAssembly = Assembly.Load(filterAssemblies[i]);
                if (currentAssembly != null)
                {
                    //通过反射动态获取类的信息
                    Type type = currentAssembly.GetType(filterAssemblies[i].Split(",")[0] + "." + className);
                    if (type == null)
                    {
                        continue;
                    }
                    //获取该类的特性值
                    var tableAttribute = type.GetCustomAttribute<TableAttribute>().Name;
                    if (tableAttribute.IsNullOrEmpty())
                    {
                        throw Oops.Oh("未找到指定类的信息");
                    }
                    return tableAttribute;
                }
                else
                {
                    throw Oops.Oh("未找到目标程序集");
                }
            }
            throw Oops.Oh("未找到指定类的信息");
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值