c# 反射获取特性值

        /// <summary>
        /// 获取属性中所有被特性标记的
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>

        public string ReturnToReality<T>(T obj) where T : class, IStu
        {
            //获取类型
            Type type = obj.GetType();
            //真实的名称
            List<string> stringList= new List<string>();
            //获取该类型所有的属性
            var propList = type.GetProperties();
            //循环所有的属性
            foreach (PropertyInfo prop in propList)
            {
                string Pro = prop.Name;
                if (prop.IsDefined(typeof(StuAttribute)))
                {
                    //得到该特性
                    var tp = prop.GetCustomAttribute<StuAttribute>();
                    if (tp != null)
                    {

                        //取该特性的值
                        Pro = tp.StuName;
                    }
                }
                stringList.Add(Pro);
            }
            return string.Join(",", stringList);
        }

/***********************************以下是特性********************************************/

/// <summary>
    /// 特性标记为 只能给属性标记
    /// </summary>
    [AttributeUsage(AttributeTargets.Property)]
    public class StuAttribute:Attribute
    {
        public string StuName;

        public StuAttribute(string stuName)
        {
            this.StuName = stuName;
        }

    }

/*************************实体 **************接口IStu 是起标记作用  接口中什么都没有*******/

public class Student:IStu
    {
        public int Id { get; set; }
        [Stu("SName")]
        public string Name { get; set; }

    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值